用VBS显示域中所有用户组及组成员
环境和需求
有一个Windows域,域名是mydomain.com。需求,显示域中的所有用户组,以及用户组中的用户ID和用户名。
制作脚本
保存下面的VBS程序代码到vbs文件中
On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.CommandText = "SELECT sAMAccountName,userAccountControl,distinguishedName FROM 'LDAP://dc=mydomain,dc=com' WHERE objectCategory='group'"
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
Set objGroup = GetObject("LDAP://" & objRecordSet.Fields("distinguishedName").Value)
WScript.Echo objGroup.sAMAccountName & "," & objGroup.displayName & "," & objGroup.description
objGroup.GetInfo
arrMemberOf = objGroup.GetEx("member")
For Each strMember in arrMemberOf
Set objGU = GetObject("LDAP://" & strMember)
WScript.echo objGroup.sAMAccountName & ":" & objGU.cn ' objGU.cn & objGU.Name & objGU.sAMAccountName
Next
objRecordSet.MoveNext
Loop
假设保存的文件名为GroupAndUsers.vbs。保存在D:
如果想只显示组名,不想显示组中的用户请删除下面代码:
objGroup.GetInfo
arrMemberOf = objGroup.GetEx("member")
For Each strMember in arrMemberOf
Set objGU = GetObject("LDAP://" & strMember)
WScript.echo objGroup.sAMAccountName & ":" & objGU.cn ' objGU.cn & objGU.Name & objGU.sAMAccountName
Next
修改下列代码中的域名为您自己的域名
objCommand.CommandText = "SELECT sAMAccountName,userAccountControl,distinguishedName FROM 'LDAP://dc=mydomain,dc=com' WHERE objectCategory='group'"
运行和测试
运行下列代码进行测试
在域中的任何一台计算机或服务器上,已管理员身份运行CMD窗口。在CMD窗口中运行下列代码进行测试。
cscript d:\GroupAndUsers.vbs
将测试结果输出到txt文件中
cscript d:\GroupAndUsers.vbs >d:\GroupAndUsers.txt