为什么我无法捕获我的非终止错误?

  • 本文关键字:终止 错误 powershell
  • 更新时间 :
  • 英文 :


我想向某人展示一个有关如何在PowerShell中捕获非终止错误的示例。

我创建了这个函数:

# This will write a non-terminating error
function NonTerminatingErrorExample {
Param($i = 5)
if ($i -gt 4) {
Write-Error "I expected a value less or equal to 4!" 
}
Write-Host "However, I can still continue the execution"
}

但是,我无法用-ErrorAction Stop抓住它

Try {
NonTerminatingErrorExample -ErrorAction Stop
} Catch {
Write-Host "Now you see this message."
}

我从未返回捕获块。为什么?

NonTerminatingErrorExample : I expected a value less or equal to 4!
In Zeile:32 Zeichen:5
+     NonTerminatingErrorExample -ErrorAction Stop
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,NonTerminatingErrorExample
However, I can still continue the execution

你的函数不是 cmdlet,因此不支持-ErrorAction。将[CmdletBinding()]添加到正文以使其成为一个,并且将支持该参数。如果您Get-Help两个版本,您可以看到差异:作为一个函数,没有[<CommonParameters>].

最新更新