powershell捕获wmi查询的异常代码

时间:2015-04-28 15:28:36

标签: powershell exception-handling try-catch wmi

我正在检查在一组计算机上使用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"
        }
    }
}

2 个答案:

答案 0 :(得分:3)

错误号存储在异常的HResult属性中。请注意,您需要将错误操作设置为Stop以使WMI错误可以捕获:

$ErrorActionPreference = 'Stop'
try {
  Get-WmiObject ...
} catch {
  $e = $_.Exception
  switch ($e.HResult) {
    0x80070005 { ... }
    default    { throw $e }
  }
}

答案 1 :(得分:0)

这最终对我有用。

catch [System.UnauthorizedAccessException]