当使用时
-ErrorAction Stop
标志,非终止错误将作为类型包装和抛出
System.Management.Automation.ActionPreferenceStopException
. 因此,一个解决方案是通过
异常树
像这样,
Try{
$connection = Test-Connection -BufferSize 32 -Count 1 -ErrorAction Stop -ComputerName "test"
return $connection.StatusCode.ToString()
}
Catch [System.Management.Automation.ActionPreferenceStopException]{
$exception = $_.Exception
#Walk through Exception tree
while ($exception.InnerException) {
$exception = $exception.InnerException
}
#Return only the last inner exception
return $exception.Message
}
Catch [Exception]{
return "Unexpected exception"
}
编辑
注意,我的代码返回了最后一个内部异常
消息
作为一根绳子。如果需要,也可以使用相同的逻辑来查找其他信息。