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"
}
}
}
The error number is stored in the
HResult
property of the exception. Note that you need to set the error action toStop
to make WMI errors catchable:This is what eventually worked for me.