最近在处理try_catch异常的时候,catch无法捕获异常信息。对命令我没有加-ErrorVariable errorvar 参数,而是用$error[0]读取当前的错误信息,无论catch用哪种异常类型都无法进入到catch里面进行处理。
代码如下:
try
{
gwmi -ComputerName "waapdf2" -Namespace "root\mscluster" -Class MSCluster_Cluster|select -ExpandProperty Name
}
catch [System.Runtime.InteropServices]
{
#测试异常能否进入
Write-Host "Error 0"
}
catch [System.Exception]
{
#测试异常能否进入
write-host "Error 11"
if ($error[0].Exception.GetType().Name -eq "COMException")
{
write-host "Error 1"
}
elseif($error[0].FullyQualifiedErrorId.StartsWith("GetWMICOMException"))
{
write-host "Error 2"
}
else{}
}
finally
{
}
错误信息:
PS C:\Windows\system32> $Error[0]
gwmi : 终结点映射器中没有更多的终结点可用。
At line:1 char:5
+ gwmi -ComputerName "waapdf2" -Namespace "root\mscluster" -Class M ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
异常类型:
PS C:\Windows\system32> $Error[0].Exception.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True COMException System.Runtime.InteropServices.ExternalException
×用微信扫描并分享