Powershell 最后使用 Ctrl-C 跳过块

2023-11-21

我正在 Powershell 中编写一个监控脚本,使用 Try/Finally 来在脚本结束时记录一条消息。该脚本旨在无限期地运行,因此我想要一种方法来跟踪意外退出。

所有其他 StackOverflow 帖子和帮助页面我检查过状态:

即使您使用 CTRL+C 停止脚本,Finally 块也会运行。如果 Exit 关键字从 Catch 块内停止脚本,Finally 块也会运行。

在实践中,我还没有发现这是真的。我正在使用以下人为的示例来测试这一点:

Try {
    While($True) {
        echo "looping"
        Start-Sleep 3
    }
} Finally {
    echo "goodbye!"
    pause
}

The Finally block here is skipped every time after a Ctrl+C (no echo, no pause), both when running as a saved script or when executing through the built-in Powershell ISE. The only output I ever get is:

looping
looping
...(repeat until Ctrl-C)

我显然错过了一些东西,但我不知道它是什么,特别是在像这样小的代码片段中。


The proper answer is that Ctrl+C breaks pipeline, as is also stated in that link, and echo uses the pipeline to process its output. Therefore, once you Ctrl+C, writing to the pipeline causes the script block to err, and to not process any further commands. Therefore, do not use commands that send output to stdout directly, and there is a lot of them that indirectly use pipeline. Write-Host, on the other hand, does not use the pipeline, and thus does not throw an error.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Powershell 最后使用 Ctrl-C 跳过块 的相关文章

随机推荐