powershell catch exception codes for wmi query

2019-09-09 19:58发布

I am checking for services using WMI on a group of computers but with some I am getting errors. How do I capture these errors so I can take approptiate action?

The query is

$listOfServices = Get-WmiObject -credential $wsCred -ComputerName $comp.name -Query "Select name, state from win32_Service"

If I get the following I want to try alternative credentials

Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) 

If I get Get-WmiObject : User credentials cannot be used for local connections I want to remove the credentials

If I get Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) or any other error I just want to report back the error.

I know I should be using a try catch block but I do not know how to specify a catch for each exception.

Here is what I have so far -

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条回答
Melony?
2楼-- · 2019-09-09 20:04

The error number is stored in the HResult property of the exception. Note that you need to set the error action to Stop to make WMI errors catchable:

$ErrorActionPreference = 'Stop'
try {
  Get-WmiObject ...
} catch {
  $e = $_.Exception
  switch ($e.HResult) {
    0x80070005 { ... }
    default    { throw $e }
  }
}
查看更多
Anthone
3楼-- · 2019-09-09 20:19

This is what eventually worked for me.

catch [System.UnauthorizedAccessException]
查看更多
登录 后发表回答