【发布时间】:2015-07-07 13:11:47
【问题描述】:
我正在一组计算机上使用 WMI 检查服务,但其中一些我遇到了错误。如何捕获这些错误以便采取适当的措施?
查询是
$listOfServices = Get-WmiObject -credential $wsCred -ComputerName $comp.name -Query "Select name, state from win32_Service"
如果我得到以下信息,我想尝试其他凭据
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
如果我收到 Get-WmiObject : User credentials cannot be used for local connections 我想删除凭据
如果我收到Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) 或任何其他错误,我只想报告错误。
我知道我应该使用 try catch 块,但我不知道如何为每个异常指定一个 catch。
这是我目前所拥有的 -
try {
$listOfServices = Get-WmiObject -credential $wsCred -ComputerName $comp.name -Query "Select name, state from win32_Service" -ErrorAction Stop
}
catch {
$e = $_.Exception
switch ($e.ErrorCode) {
0x80070005 {
$listOfServices = Get-WmiObject -credential $svrCred -ComputerName $comp.name -Query "Select name, state from win32_Service" -ErrorAction Stop
}
default {
write "Error code: $e.ErrorCode"
write "Error details: $e.ErrorDetails"
write "Full error: $e"
}
}
}
【问题讨论】:
标签: powershell exception-handling try-catch wmi