如何退出函数中的每个循环?

时间:2013-12-17 01:11:21

标签: vbscript foreach error-handling wmi onerror

我有以下函数,用于递归读取计算机上的所有WMI名称空间,具体取决于传递的名称空间(默认情况下,脚本调用ReadWMI(“root”)。如果WMI名称空间包含名称sms或ccm,我想测试写入该命名空间以验证写入工作。如果写入WMI在该函数中失败,我想退出For循环并完全退出该函数。

我注意到当我退出for或退出函数(使用Exit For或Exit Function)时,我返回到Next而不是完全退出该函数。这会导致许多问题,其他名称空间可以成功写入。

Function ReadWMI(strNameSpace)

Dim oWMI, colNameSpaces, objNameSpace, sFullNamespace

'ReadWMI = "True"

WMI_ReadRepository = "Healthy"

On Error Resume Next

'Verify all namespaces

Set oWMI = GetObject("winmgmts:\\" & sComputer & "\" & strNameSpace)

If Err.Number <> 0 Then

    ReadWMI = "False"

    WMI_ReadRepository = "Unhealthy"

    oLog.WriteLine Now()& " - " &  "ReadWMI(): Failed to bind to WMI namespace " & strNamespace & ". Stopping WMI Verification"
    oLog.WriteLine Now()& " - " &  "ReadWMI(): Error Code: " & Err.Number
    'oLog.WriteLine Now()& " - " &  "ReadWMI(): Error Description: " & Err.Description
    Err.Clear

    Exit Function

Else

    oLog.WriteLine Now()& " - " &  "ReadWMI(): Successfully connected to WMI namespace " & strNamespace 

End If  

Set colNameSpaces = oWMI.InstancesOf("__NAMESPACE")

For Each objNameSpace In colNameSpaces

    sFullNamespace = LCase(strNamespace & "\" & objNamespace.Name)



    If InStr(sFullNamespace,"ccm") Or InStr(sFullNamespace,"sms") > 0 Then

        oLog.WriteLine Now()& " - " &  "ReadWMI(): Writing to " & sFullNamespace & " WMI Namespace if WMIWriteRepository set to TRUE"

        If WMIWriteRepository = True Then

            If WriteWMI(sFullNamespace) = "False" Then

                oLog.WriteLine Now()& " - " &  "ReadWMI(): Failed to write to namespace " & sFullNamespace

                WMI_ReadRepository = "Unhealthy"

                'ReadWMI = "False"

                Exit Function

            End If

        Else

            oLog.WriteLine Now()& " - " &  "ReadWMI(): WMIWriteRepository set to False or OS is a Server. Will not write to repository."    

        End If


    End If


    'Call VerifyWMI again to run through the next namespace     

    Call ReadWMI(sFullNamespace)

Next



'ReadWMI = "True"

'WMI_ReadRepository = "Healthy"

Set oWMI = Nothing

On Error Goto 0

End Function

1 个答案:

答案 0 :(得分:2)

如果出现问题并且您想跳出递归函数调用,请返回值False(取消注释脚本中的'ReadWMI = "False")。

你在下一个声明之前的最后一个声明必须测试WMI的读数是否正确,而不是

Call ReadWMI(sFullNamespace)

使用

If ReadWMI(sFullNamespace) = "False" Then
    Exit For
End If

Protip:停止使用“字符串布尔”,它们很慢,并且错误在拐角处引诱你在后面咬你("True" <> "true" <> "Treu" <> "True ")。只需使用TrueFalse即可。无论何时想要向字符串输出布尔值,它都会自动转换为正确的字符串值:

MsgBox True & " / " & False 
' Output: "True / False"