2008年9月25日星期四

AD用户删除脚本

最近在客户那做一个AD相关的项目,要实现一个批量删除AD用户的需求,可以通过以下的AD脚本+txt文件实现批量功能:(vbs脚本如下)
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("D:\Test\Book.txt", ForReading)

Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
'--------------Start--------------
TARGET_OU = "JT" '删除帐号所在的OU
samAccountName=strNextLine '删除帐号的samAccountName


Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

Dim rootDSE
Set rootDSE = GetObject("LDAP://rootDSE")
BaseDN = rootDSE.Get("defaultNamingContext")

DC= replace(BaseDN,"DC=",",")
DC= replace(DC,",,",".")
DC=right(DC,len(DC)-1)

objCommand.CommandText = ";(&(objectcategory=person)(objectclass=user)(samAccountName="&samAccountName&"));cn,ADsPath,distinguishedName;subtree"
'MsgBox objCommand.CommandText
Set objRecordSet = objCommand.Execute
If objRecordSet.RecordCount>0 Then
cn=objRecordSet.Fields("cn") '查找要删除帐号的CN名.因为删除的时候要指定CN名,我不知道这里查出来的,带不带“cn“,如果不带,手工加一下
ComDNPath = objRecordSet.Fields("distinguishedName")'得到distinguishedName,并在如下的代码中重新组合成OU的LDAP
End If
'MsgBox ComDNPath
arrDirectoryLocation = Split(ComDNPath,",")
'MsgBox Ubound(arrDirectoryLocation)
For i = 1 to Ubound(arrDirectoryLocation)
If i = 1 Then
strComOU = arrDirectoryLocation(i)
Else
strComOU = strComOU & "," & arrDirectoryLocation(i)
End If
Next
Set objOU = GetObject("LDAP://" & strComOU)
If objRecordSet.RecordCount>0 Then
'MsgBox arrDirectoryLocation(0)
objOU.Delete "user", arrDirectoryLocation(0)
End If
'--------------End----------------
Loop

objTextFile.Close
set objTextFile = Nothing

另外附上两个参考vbs脚本库的地址:http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/usersgroups/users/
http://www.microsoft.com/china/technet/community/scriptcenter/scripts/ad/default.mspx
微软脚本中心:http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx