powershell catch exception codes for wmi query

0

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"
        }
    }
}
powershell
exception-handling
try-catch
wmi
asked on Stack Overflow Apr 28, 2015 by user2369812 • edited Apr 29, 2015 by user2369812

2 Answers

3

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 }
  }
}
answered on Stack Overflow Apr 28, 2015 by Ansgar Wiechers • edited Apr 29, 2015 by Ansgar Wiechers
0

This is what eventually worked for me.

catch [System.UnauthorizedAccessException]
answered on Stack Overflow Apr 30, 2015 by user2369812

User contributions licensed under CC BY-SA 3.0