查询 AD 以获取下一个可用计算机名称的脚本失败并出现错误 "Loop without Do"

Script to query AD for next available computer name fails with error "Loop without Do"

我在网上找到了这个 VBScript,它可以查询 AD 以获取下一个可用的计算机名称。当我尝试 运行 时,出现以下错误:

Line 51 character 1
Loop without Do

有问题的脚本是:

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

是否有人能够确定此代码的问题所在?

您需要在最终的 Loop 语句之前添加一个 End If,该语句就在结果赋值之前。实际上,Loop 正试图关闭一个 If 块,这导致了您的错误。

       ...

       if PCVar = "" Then
          PCExist=True
       END IF

     <b>End If</b> 'Add this

  Loop

  AvailablePCName = PCName

End Function