powershell catch exception codes for wmi query

↘锁芯ラ 提交于 2020-01-07 09:04:31

问题


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"
        }
    }
}

回答1:


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 }
  }
}



回答2:


This is what eventually worked for me.

catch [System.UnauthorizedAccessException]


来源:https://stackoverflow.com/questions/29923588/powershell-catch-exception-codes-for-wmi-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!