给定此脚本:
& non_existent_cmd
echo "I don't want this to run"
在运行& non_existent_cmd
时,引发非终止错误的最简单方法是什么,这样以下echo
命令就永远不会运行。
作为参考,脚本(如上所述)当前输出:
&:术语"non_existent_cmd"未被识别为cmdlet的名称,函数、脚本文件或可操作程序。检查姓名的拼写,或者,如果包含路径,请验证该路径是否正确,然后重试。行:1字符:3+&non_existent_cmd+~~~~~~~~~~~~~~~~+CategoryInfo:ObjectNotFound:(non_existent_cmd:String)[],CommandNotFoundException+FullyQualifiedErrorId:CommandNotFoundException我不希望它运行
您可以将会话的$ErrorActionPreference
设置为Stop
。这将使任何错误成为终止错误。
如果你只想在错误时终止调用,你可以这样做:
$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
& non_existent_cmd
echo "I don't want this to run"
$ErrorActionPreference = $eap
也许试试这个?
try { & non_existent_cmd }
catch { Break }
"I don't want this to run"