当 $ErrorActionPreference 设置为 stop 时,您能否在 powershell 脚本中重定向错误?

qwe*_*234 4 powershell

我有一些 PowerShell 脚本,其中包含以下内容:

$ErrorActionPreference = "stop"
trap { Write-Error $_.Exception; }
Run Code Online (Sandbox Code Playgroud)

使用 powershell 重定向运算符从 powershell 窗口调用脚本时:

c:\somescript.ps1 2> c:\error.txt
Run Code Online (Sandbox Code Playgroud)

它只会将错误打印到 powershell 窗口,而不会将其重定向到文件。如果我从脚本中删除 $ErrorActionPreference = "stop",则重定向有效,但这不是一个可行的选择,因为我们需要脚本在遇到任何错误时终止。我也尝试过使用 '*>',但结果相同。

有什么方法可以将错误重定向到文件而无需更改所有脚本?

mkl*_*nt0 5

您的方法的问题在于$ErrorActionPreference = "Stop"

  • 立即停止(异常中止)整个脚本命令调用它c:\somescript.ps1 2> c:\error.txt

  • 这意味着重定向2> c:\error.txt进行,并且在控制台中显示错误消息,而不是在指定的文件被捕获。

解决方法是有点麻烦:

将另一个脚本的调用包含在一个try ... catch语句中,如下所示:FatalBulletHit 致敬,寻求他的帮助。

$ErrorActionPreference = 'Stop'

try {

 c:\somescript.ps1

} catch {

  # Now you can write the error record to the file.
  $_ > c:\error.txt

  # == Optional additional actions.

  # If desired, you can additionally 
  # emit the error too (write it the error to the error stream).
  # !! -ErrorAction Continue is necessary in order to override
  # !! $ErrorActionPreference = 'Stop'.
  # !! Without it, the use of Write-Error itself would cause an - uncaught -
  # !! script-terminating (fatal) error. 
  Write-Error -ErrorRecord $_ -ErrorAction Continue

  # Exit the script with a nonzero exit code to signal failure
  # (which is useful if your script is called from *outside*
  # PowerShell).
  exit 1

}
Run Code Online (Sandbox Code Playgroud)

在块中调用之前需要使用-ErrorAction Continue(或临时设置$ErrorActionPreference = 'Continue')以避免导致脚本终止(致命)错误令人惊讶;如果您的脚本/函数是高级脚本/函数而您改用它,它也适用。Write-Errorcatch$PSCmdlet.WriteError($_)