【问题标题】:powershell catch exception codes for wmi querypowershell 捕获 wmi 查询的异常代码
【发布时间】:2015-07-07 13:11:47
【问题描述】:

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

【问题讨论】:

    标签: powershell exception-handling try-catch wmi


    【解决方案1】:

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

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

    【讨论】:

    • 这似乎不起作用,因为 $e.errorcode 返回整个消息而不仅仅是输出的代码 - System.UnauthorizedAccessException:访问被拒绝。 (来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))在 System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
    • @user2369812 在这种情况下使用HResult 属性。您可能还需要设置$ErrorActionPreference 而不是使用-ErrorAction。查看更新的答案。
    【解决方案2】:

    这最终对我有用。

    catch [System.UnauthorizedAccessException]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      相关资源
      最近更新 更多