powershell捕获wmi查询的异常代码 [英] powershell catch exception codes for wmi query
问题描述
code> $ listOfServices = Get-WmiObject -credential $ wsCred -ComputerName $ comp.name -Query从win32_Service中选择名称,状态
如果我得到以下内容,我想尝试替代凭据
Get-WmiObject:Access被拒绝。 (HRESULT的异常:0x80070005(E_ACCESSDENIED))
如果我得到 Get- WmiObject:用户凭据不能用于本地连接
我要删除凭据
如果我得到 Get-WmiObject :RPC服务器不可用。 (从HRESULT的异常:0x800706BA)
或任何其他错误我只想报告错误。
我知道我应该使用一个尝试catch块,但我不知道如何为每个异常指定一个catch。
这是我到目前为止 -
try {
pre>
$ listOfServices = Get-WmiObject -credential $ wsCred -ComputerName $ comp.name -Query从win32_Service中选择名称,状态-ErrorAction Stop
}
catch {
$ e = $ _。异常
开关($ e.ErrorCode){
0x80070005 {
$ listOfServices = Get-WmiObject-credential $ svrCred -ComputerName $ comp.name -Queryselect name,state from win32_Service-ErrorAction Stop
}
default {
write错误代码:$ e.ErrorCode
写错误详细信息:$ e.ErrorDetails
write完整错误:$ e
}
}
}
解决方案错误号存储在异常的
HResult
属性中。请注意,您需要将错误操作设置为停止
以使WMI错误可捕获:$ ErrorActionPreference ='Stop'
try {
Get-WmiObject ...
} catch {
$ e = $ _例外
开关($ e.HResult){
0x80070005 {...}
默认{throw $ e}
}
}
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 credentialsIf 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:$ErrorActionPreference = 'Stop' try { Get-WmiObject ... } catch { $e = $_.Exception switch ($e.HResult) { 0x80070005 { ... } default { throw $e } } }
这篇关于powershell捕获wmi查询的异常代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!