连接和拆分返回ubound(array)+ 1项

时间:2011-07-31 08:39:46

标签: loops vbscript split

我想知道我在哪里出错了。以下脚本将始终在数组末尾返回一个空项。为什么?我不认为这是记录集的问题。有任何想法吗?

function allServers 
    Set adoCommand = CreateObject("ADODB.Command")
    Set adoConnection = CreateObject("ADODB.Connection")
    adoConnection.Provider = "ADsDSOObject"
    adoConnection.Open "Active Directory Provider"
    Set adoCommand.ActiveConnection = adoConnection

    Set objRootDSE = GetObject("LDAP://RootDSE")

    strDNSDomain = objRootDSE.Get("defaultNamingContext")
    strBase = "<LDAP://" & strDNSDomain & ">"
    strFilter = "(&(objectCategory=computer)(operatingsystem=*server*)(!userAccountControl:1.2.840.113556.1.4.803:=2))"
    strAttributes = "name,distinguishedname,dnshostname"
    strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
    adoCommand.CommandText = strQuery
    adoCommand.Properties("Page Size") = 100
    adoCommand.Properties("Timeout") = 30
    adoCommand.Properties("Cache Results") = False

    Set adoRecordset = adoCommand.Execute
    dim strList, i
    Do Until adoRecordset.EOF
        strList = strList & adoRecordSet.Fields("name").Value & ","
    adoRecordset.MoveNext
    loop
    adoRecordset.Close
    adoConnection.Close

    arr = split(strList, ",",-1,1)
    allServers = arr
end function

arr = allservers
For i = 0 to UBound(arr)
    wscript.echo  i & ":" & arr(i)
next

1 个答案:

答案 0 :(得分:0)

你的循环:

Do Until adoRecordset.EOF
    strList = strList & adoRecordSet.Fields("name").Value & ","
    adoRecordset.MoveNext
loop

在strList的末尾放置最后一个/尾随/终止“,”。 Split()将“,”视为分隔符(不是终止符),因此生成的数组有一个虚假的最后一个空元素。

为了避免这种情况,你可以在循环中连接"," & value并使用Mid()删除前面的“,”。但是为什么不使用“SELECT COUNT”或Recordset.Count来在循环之前对数组进行维度并将值赋给其元素,或者 - 甚至更好 - Recordset.GetRows()直接得到一个(尽管是2 dim)数组 - &gt ;没有连结,没有分裂,没有问题。