Powershell 为什么写入错误会终止脚本?
我在web上读到的所有内容都告诉我,Write Error会写入错误流,但不会终止脚本,但当运行以下脚本时,它显然会终止脚本Powershell 为什么写入错误会终止脚本?,powershell,Powershell,我在web上读到的所有内容都告诉我,Write Error会写入错误流,但不会终止脚本,但当运行以下脚本时,它显然会终止脚本 Write-Error "This should not terminate the script..." Write-Information "... and it hasn't" 输出为: D:\MyBitsAndBobs\writeerrortest.ps1 : This should not terminate the script... At D:\MyBit
Write-Error "This should not terminate the script..."
Write-Information "... and it hasn't"
输出为:
D:\MyBitsAndBobs\writeerrortest.ps1 : This should not terminate the script...
At D:\MyBitsAndBobs\writeerrortest.ps1:3 char:1
+ Write-Error "This should not terminate the script..."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,writeerrortest.ps1
“而且它没有”的信息显然从未被执行过。
有人能解释一下这种明显出乎意料的行为吗?这与默认的工作方式有关 根据文件: $InformationPreference变量值决定 您提供的用于写入信息的消息是否显示在 脚本操作中的预期点。因为默认值 默认情况下,此变量的值为SilentlyContinue 不显示消息。如果不想更改 $InformationPreference,您可以通过添加 InformationAction是命令的公共参数 因此,在您的情况下,要么将
写入信息
更改为写入主机
,要么使用:
Write-Error "This should not terminate the script..."
Write-Information "... and it hasn't" -InformationAction Continue
输出:
查看您的
$ErrorActionPreference
变量。默认情况下,它设置为“继续”,实际上不会终止脚本。在你的情况下,它可能会停止。将其更改为$ErrorActionPreference=[System.Management.Automation.ActionPreference]::继续并再次运行脚本。有比这两个更多的设置,请浏览它们 如果您将Write Information
更改为Write Host
,您将看到这两条消息show us your$ErrorActionPreference
My bad,我应该设置$InformationPreference=“Continue”我提出的问题很糟糕,是我的错。如果我设置了$InformationPreference=“Continue”,那么Write Error不会终止脚本,但是如果我也设置了$ErrorActionPreference=“Stop”,那么Write Error会终止脚本,所以问题应该是,为什么Write Error会在$ErrorActionPreference=“Stop”时终止脚本,就其本身而言,这是一个错误。@Dave好吧,这不是什么悖论,这只是它如何通过设计工作。写入错误生成错误,ErrorActionPreference控制如何处理该错误,Stop使其成为终止错误。
Write-Error "This should not terminate the script..."
Write-information "... and it hasn't" -InformationAction Continue : This should not terminate the script...
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
... and it hasn't