我具有以下旨在根据传递的 namespace 递归读取计算机上所有WMI namespace 的函数(默认情况下,脚本调用ReadWMI(“root”)。如果WMI namespace 包含名称sms或ccm ,我想测试对该 namespace 的写入以验证写入工作,如果在该函数中写入WMI失败,我想退出For循环并完全退出该函数。
我注意到的是,当我退出for或退出函数(使用Exit For或Exit Function)时,我将返回Next,而不是完全退出该函数。这会导致许多其他 namespace 可以成功写入的问题。
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
最佳答案
如果出了点问题,并且您想跳出递归函数调用,则将返回值设为False
(在脚本中取消注释'ReadWMI = "False"
)。
下一条之前的最后一条语句必须测试WMI的读数是否正确,因此,
Call ReadWMI(sFullNamespace)
采用
If ReadWMI(sFullNamespace) = "False" Then
Exit For
End If
提示:停止使用“字符串 bool(boolean) 值”,它们速度很慢,并且错误不断逼近您的背后(
"True" <> "true" <> "Treu" <> "True "
)。只需使用True
和False
即可。每当您要将 bool(boolean) 值输出到字符串时,它都会自动转换为正确的字符串值:MsgBox True & " / " & False
' Output: "True / False"
关于vbscript - 如何退出函数中的每个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20624113/