以前写过一段脚本是从AD域中查询AD用户信息。但是如果从WorkGroup上就无法得到结果了。下面的一段脚本可以实现从WorkGroup查询域账户信息。
注意:运行之前先将DC服务器以及账户名和密码替换,然后保存成VBS。如果要查询其他信息可以更改对应的Filter,category和Class.
Option Explicit
Dim objRootDSE, strDNSDomain, adoCommand, adoConnection
Dim strBase, strFilter, strAttributes, strQuery, adoRecordset
Dim strDN, objNS, strServer
Const ADS_SECURE_AUTHENTICATION = &H1
Const ADS_SERVER_BIND = &H200
' Specify a server (Domain Controller).
strServer = "Allen.home"
' Determine DNS domain name. Use server binding and alternate
' credentials. The value of strDNSDomain can also be hard coded.
Set objNS = GetObject("LDAP:")
Set objRootDSE = objNS.OpenDSObject("LDAP://" & strServer & "/RootDSE", _
strUser, strPassword, _
ADS_SERVER_BIND Or ADS_SECURE_AUTHENTICATION)
strDNSDomain = objRootDSE.Get("defaultNamingContext")
' Use ADO to search Active Directory.
' Use alternate credentials.
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Properties("User ID") = "youruser"
adoConnection.Properties("Password") = "yourPassword"
adoConnection.Properties("Encrypt Password") = True
adoConnection.Properties("ADSI Flag") = ADS_SERVER_BIND _
Or ADS_SECURE_AUTHENTICATION
adoConnection.Open "Active Directory Provider"
Set adoCommand.ActiveConnection = adoConnection
' Search entire domain. Use server binding.
strBase = "<LDAP://" & strServer & "/" & strDNSDomain & ">"
' Search forspecial users.
strFilter = "(&(objectCategory=person)(objectClass=user)(samaccountname=mycode))"
'only get display name for user
strAttributes = "name"
' Construct the LDAP query.
strQuery = strBase & ";" & strFilter & ";" _
& strAttributes & ";subtree"
' Run the query.
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute
' Enumerating theresult(for me only have one result)
Do Until adoRecordset.EOF
' Retrieve values.
strDN = adoRecordset.Fields("name").Value
Wscript.Echo strDN
adoRecordset.MoveNext
Loop
' Clean up.
adoRecordset.Close
adoConnection.Close
更多信息可以参考:
Searching with ActiveX Data Objects (ADO)
http://msdn.microsoft.com/en-us/library/Aa746471.aspx
Search Filter Syntax