枚举所有用户,包括SID

时间:2015-09-02 12:18:43

标签: vbscript active-directory ldap

我已经编写了一个VBScript来列出AD中的所有用户和所选信息。但我想将SID添加到用户信息列表中,而无需连接到每个用户对象。有什么想法吗?

' Set up the connection to the domain
Set objConnection = CreateObject( "ADODB.Connection" )
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

' Configure the Active Direcctory connection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

' Filter to search AD with
strFilter = "(&(objectCategory=person)(objectClass=user))"

' Attributes to return with the search
strAttrib = "sAMAccountName,cn,sn,givenName,title,department,company,physicalDeliveryOfficeName,mail,telephoneNumber,l,st,postalCode,co,whenCreated,whenChanged,manager,userAccountControl,objectSid"

' Build the AD query
strQuery = "<LDAP://dc=yourdomain,dc=com>;" & strFilter & ";" & strAttrib & ";subtree"

' Create the file system object
Set objFSO = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFSO.CreateTextFile( "users.csv" )
objFile.WriteLine """Domain"",""User ID"",""CN"",""Last Name"",""First Name"",""Email"",""SID"""

' Execute the query
objCommand.CommandText = strQuery
Set objRecordSet = objCommand.Execute

Do Until objRecordSet.EOF
    objFile.WriteLine objRecordSet.Fields( "objectSid" ).Value
Loop

不幸的是,这没有任何回报。

1 个答案:

答案 0 :(得分:1)

首先,您有一个无限Do循环,因为它缺少objRecordSet.MoveNext语句。

话虽如此,您问题的最可能原因是objectSid属性的数据类型。 Active Directory中的SID不以字符串形式存储,而是以二进制格式存储。如果您检查TypeName(objRecordSet.Fields("objectSid").Value)的结果,则会看到它Byte(),因此将原始值写入文本文件不会产生可读输出。您需要convert SID从二进制到字符串形式,以获得人类可读的结果:

Function DecodeSID(binSID)
  ReDim o(LenB(binSID))

  ' Convert binary string to octet array.
  For i = 1 To LenB(binSID)
    o(i-1) = AscB(MidB(binSID, i, 1))
  Next

  ' Convert octet array to (human-readable) SID string.
  sid = "S-" & CStr(o(0)) & "-" & OctetArrayToString _
        (Array(o(2), o(3), o(4), o(5), o(6), o(7)))
  For i = 8 To (4 * o(1) + 4) Step 4
    sid = sid & "-" & OctetArrayToString(Array(o(i+3), o(i+2), o(i+1), o(i)))
  Next

  DecodeSID = sid
End Function

Function OctetArrayToString(arr)
  v = 0
  For i = 0 To UBound(arr)
    v = v * 256 + arr(i)
  Next

  OctetArrayToString = CStr(v)
End Function