Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 如何读取抛出的错误内容并在IF语句中使用它_Powershell - Fatal编程技术网

Powershell 如何读取抛出的错误内容并在IF语句中使用它

Powershell 如何读取抛出的错误内容并在IF语句中使用它,powershell,Powershell,我想用try{}/Catch{}来“抓取”异常的内容,并使用IF来搜索其中的内容。有人能告诉我如何使用$PSItem.Exception吗?谢谢大家! try { get-process ... } catch { if (PSItem.Exception ....) { Write-Error -Message "just move on !" -ErrorAction continue } else { throw PSItem.

我想用try{}/Catch{}来“抓取”异常的内容,并使用IF来搜索其中的内容。有人能告诉我如何使用$PSItem.Exception吗?谢谢大家!

try {
  get-process ...
}
catch {
    if (PSItem.Exception ....) { 
        Write-Error -Message "just move on !" -ErrorAction continue
    }
    else {
        throw PSItem.Exception
    }
}

从try/catch块抛出的项(对于中的任何异常都是如此)是
ErrorRecord
类型(您可以在msdn上看到其成员)。在此记录中,实际异常位于
$PSItem.exception
(或
$\ucode>下,而不是
$PSItem
);此成员在
异常
上的
消息
成员下还有一个异常消息字符串。如果使用
ErrorRecord#ToString
方法,则无需深入挖掘成员即可直接获得:

"$PSItem"
然后,您可以查看错误消息,查看您喜欢的内容:

if ("$PSItem" -like '*Access denied*') {
请注意,不要重新抛出异常,只需像这样抛出原始错误记录:

else {
    throw
}

什么是“something”?您可以直接在catch块中使用
$\u.Exception.Message
来捕获唯一的错误消息。除此之外,有时还需要使用任何.net异常的
InnerException
属性更深入地查看异常。当链停止时,该属性的值为空。例如
$\异常.InnerException.InnerException