鉴于此脚本:
var fun = map["Dog"];
运行& non_existent_cmd
echo "I don't want this to run"
时引发非终止错误的最简单方法是什么,以便以下& non_existent_cmd
命令永远不会运行。
作为参考,脚本(如上所述)当前输出:
& : The term 'non_existent_cmd' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:3 + & non_existent_cmd + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (non_existent_cmd:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I don't want this to run
答案 0 :(得分:3)
您可以将会话的$ErrorActionPreference
设置为Stop
。这将使任何错误成为终止错误。
如果您只希望该呼叫在出错时终止,您可以执行以下操作:
$eap = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
& non_existent_cmd
echo "I don't want this to run"
$ErrorActionPreference = $eap
答案 1 :(得分:2)
也许试试这个?
try { & non_existent_cmd }
catch { Break }
"I don't want this to run"