gpt4 book ai didi

Powershell CommandNotFoundException 正在终止?

转载 作者:行者123 更新时间:2023-12-02 18:32:13 27 4
gpt4 key购买 nike

执行这样的脚本时:

nonexistingcommand
echo "Hello"

我得到:

nonexistingcommand : The term 'nonexistingcommand' 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 D:\Playground\powershell\Test.ps1:2 char:1
+ nonexistingcommand
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (nonexistingcommand:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Hello

因此,CommandNotFoundException 似乎是一个非终止错误。那么为什么如果我

try {
nonexistingcommand
}
catch [System.Management.Automation.CommandNotFoundException] {
throw
}
echo "Hello"

在这种情况下,它将退出并且不打印“Hello”。

这是为什么?

最佳答案

不幸的是,PowerShell 有两种类型的终止错误:

  • 语句终止错误,默认情况下仅终止封闭的语句

    • 默认情况下,执行继续,即使用下一个语句(在您的情况下echo "Hello")

    • CommandNotFoundException 就是此类错误的一个实例。

    • 相比之下,如果有进一步的管道输入可用(例如,Get-ChildItem NoSuchDir,\对于不存在的目录发出非终止错误。NoSuchDir,然后继续成功报告现有目录。\)

  • 脚本终止(线程终止)错误,该错误会终止封闭的脚本和整个调用堆栈

    • 此类错误是由 throw statement 触发的从 PowerShell 代码调用,而不是二进制(编译的)cmdlet。

try { ... } catch { ... } finally { ... } statement 区分这两种子类型:它捕获它们两者

  • 鉴于您的 catch block 包含无参数 throw 语句,该语句隐式中继触发错误的错误,因此您实际上正在转变语句-脚本中的终止错误-终止脚本,因此执行在此结束。

同样,设置 $ErrorActionPreference preference variable 'Stop' 会导致所有类型的错误(由PowerShell命令[1]发出),包括>非终止的,中止整体执行;换句话说:终止和语句终止错误都会提升为脚本终止错误。


有关 PowerShell 极其复杂的错误处理的全面概述,请参阅 GitHub docs issue #1583 .


[1] 至少在控制台(终端)中外部程序的本地前台调用中,默认情况下stderr输出不是 通过 PowerShell 的错误流路由,因此不受 $ErrorActionPreference 影响。
但是,在 PowerShell v7.1 及更低版本(包括 Windows PowerShell)中,使用 2> 重定向确实通过 PowerShell 的错误流路由 stderr,这可能会产生意外的副作用。此问题将在 v7.2 中修复。
请注意,该行为是 PowerShell 特定于主机的行为,并且适用于主机 ConsoleHost(使用 $host 获取主机信息)。 其他主机仍然总是通过错误流路由stderr,这显着影响远程处理后台作业

关于Powershell CommandNotFoundException 正在终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69276210/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com