如何忽略 Powershell 中的错误并让它继续?

Jak*_*ake 56 powershell

我正在尝试查看一个进程是否在多台服务器上运行,然后将其格式化为表格。

get-process -ComputerName server1,server2,server3 -name explorer | Select-Object processname,machinename
Run Code Online (Sandbox Code Playgroud)

这是最简单的部分 - 当进程不存在或服务器不可用时,powershell 会输出一个巨大的丑陋错误,弄乱表格并且不会继续。例子

Get-Process : Couldn't connect to remote machine.At line:1 char:12 + get-process <<<<  -ComputerName server1,server2,server3 -name explorer | format-table processname,machinename
+ CategoryInfo          : NotSpecified: (:) [Get-Process], InvalidOperatio   nException    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Power   Shell.Commands.GetProcessCommand
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?如果进程不可用或正在运行,我仍希望收到通知。

Bar*_*Vos 66

添加-ErrorAction SilentlyContinue到您的命令中。

当它不是错误而是未处理的异常时,您应该添加-EV Err -EA SilentlyContinue, 以捕获异常。(EA是 的别名ErrorAction)

然后,您可以通过查看脚本来评估错误 $Err[0]


小智 18

简短回答:$ErrorActionPreference = 'SilentlyContinue'在代码的开头 添加,这样您就不需要添加-ErrorAction SilentlyContinue到每个命令中

长答案: https : //www.gitbook.com/book/devopscollective/the-big-book-of-powershell-error-handling/details

  • 请注意区别:“继续”(默认设置)继续执行,但将错误写入控制台(如果我正确地阅读了他的内容,该操作似乎想要摆脱它)。“SilentlyContinue”完全抑制所有错误消息。 (2认同)
  • [**不要那样做** #17:使用 `$ErrorActionPreference = 'SilentlyContinue'` 消除错误](http://powershell-guru.com/dont-do-that-17-silent-errors-with -erroractionpreference-silentlycontinue/) (2认同)
  • gitbook 链接已失效。我认为这是相关内容的新链接:https://devops-collective-inc.gitbook.io/the-big-book-of-powershell-error-handling/controlling-error-reporting-behavior-and-拦截错误 (2认同)