查询AD以查找下一个可用计算机名称的脚本失败,并显示错误“Loop without Do”

时间:2015-05-20 13:09:27

标签: vbscript

我发现这个VBScript在线,应该查询AD以获取下一个可用的计算机名称。当我尝试运行它时,我收到以下错误:

  

第51行第1个字符   循环没有做

有问题的剧本是:

StrAvailableName = FindAvailableName("TestWS")

Function FindAvailableName(StrPrefix)
    '*****************************************
    '* Search for an available computer name *
    '*****************************************
    Const ADS_SCOPE_SUBTREE = 2
    Dim nCount, PCName,PCExist
    Dim objConnection, objCommand,objRecordSet,PCVar

    nCount = 1
    PCName = StrPrefix & "0" & nCount
    PCExist = False

    Do Until PCExist 
        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 

        'Enter your LDAP search root for your domain here 'LDAP://dc=corp,dc=com'
        objCommand.CommandText = "SELECT ADsPath FROM 'LDAP://dc=test-dc,dc=test,dc=local' WHERE objectCategory='computer' " & "AND name=' " & PCName & "'"
        Set objRecordSet = objCommand.Execute

        PCVar = ""
        if not (objRecordSet.EOF And objRecordSet.BOF) Then 
            objRecordSet.MoveFirst
            Do Until objRecordSet.EOF
                WScript.Echo objRecordSet.Fields("ADsPath").Value
                PCVar = objRecordSet.Fields("ADsPath").Value
                objRecordSet.MoveNext
            Loop
            nCount = nCount + 1
            if nCount < 10 then
                PCName = StrPrefix & "0" & nCount
            else 
                PCName = StrPrefix & nCount
            End If

            IF PCVar = "" Then
                PCExist = True
            END IF

    Loop

    AvailablePCName = PCName

End Function

是否有人能够识别此代码的问题是什么?

1 个答案:

答案 0 :(得分:3)

您需要在最终End If语句之前添加Loop,该语句位于结果分配之前。事实上,Loop正在尝试关闭If块,这会导致您的错误。

       ...

       if PCVar = "" Then
          PCExist=True
       END IF

     End If 'Add this

  Loop

  AvailablePCName = PCName

End Function