如何仅在脚本出现红色错误时记录事件日志?

How to log an eventlog only when the script gives a red error?

我想要做的是 - 在事件日志中记录一个事件 - 应用程序, 仅当预定脚本在该会话中出现任何红色错误时...

我知道如何使用 Write-EventLog 记录它, 但不能将其限制为仅在出现红色错误时提示可能有错误。

非常感谢您的回复!

一种方法是在您的语句之前清除 $Error,然后检查是否发生错误:

$Error.Clear()
Invoke-Something
if ($Error.Count -gt 0) {
  Write-EventLog ...
}

或者您可以将所有错误转换为 terminating errors 并使用 try..catch 语句:

$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
try {
  Invoke-Something
} catch {
  Write-EventLog ...
}
$ErrorActionPreference = $eap