Wednesday, January 7, 2009

Generic AD Scripting

Here is a good way to find your current domain's LDAP path without hard coding it in your script. This is handy if you write scripts to do AD reporting and simply want them to run against the current domain wihtout updating your LDAP strings in your code.



Set rootDSE = GetObject(ldap://RootDSE/)
DomainContainer = rootDSE.Get("defaultNamingContext")
If Instr(DomainContainer, ",") then
arLDAPPath = Split(DomainContainer, ",")
strDomain = Replace(arLDAPPath(0),"DC=","")
End If



This is useful if you want to do something like this: (A SUB that when called writes a CSV with active account info)



Sub GetEnabledUsers(DomainContainer, strDomain)

set objOut = objFSO.CreateTextFile("EnabledUsers_" & strDomain & ".csv")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000

objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE objCommand.CommandText = _
";(objectCategory=User)" & _ ";displayname,sAMAccountname,mail,userAccountControl;subtree"

Set objRecordSet = objCommand.Execute
objOut.writeline """" & "Name" & """" & "," & """" & "UserID" &_
"""" & "," & """" & "Email Address" & """"
intCounter = 0
Do Until objRecordset.EOF
intUAC=objRecordset.Fields("userAccountControl")
If intUAC AND 2 Then
'Ignore
Else
objOut.writeline """" & objRecordset.Fields("displayname") & """" &_
"," &_ """" & objRecordset.Fields("sAMAccountname") & """" &_
"," & """" & objRecordset.Fields("mail") & """"
intCounter = intCounter + 1
End If

objRecordset.MoveNext
Loop


objOut.close
WScript.Echo VbCrLf & "A total of " & intCounter & " accounts"
objConnection.Close
End Sub

No comments: