使用 Ctrl-C 跳过 Powershell 最后块 [英] Powershell Finally block skipped with Ctrl-C

查看:103
本文介绍了使用 Ctrl-C 跳过 Powershell 最后块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a monitoring script in Powershell using a Try/Finally to log a message should the script end. The script is intended to run indefinitely, so I want a way to track unintended exiting.

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

Every other StackOverflow post and Help page I've checked states:

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

A Finally block runs even if you use CTRL+C to stop the script. A Finally block also runs if an Exit keyword stops the script from within a Catch block.

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

In practice, I have not found this to be true. I'm using the following contrived example to test this out:

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

Finally 块每次在 Ctrl+C(无回声,无暂停)后都会被跳过,无论是作为保存的脚本或通过内置 Powershell ISE 执行时.我得到的唯一输出是:

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)

我显然错过了一些东西,但我不知道它是什么,尤其是在这么小的代码片段中.

I've clearly missed something, but I have no idea what it is, especially in a code snippet as small as this.

推荐答案

正确的答案是 Ctrl+C 中断管道,正如该链接中所述,echo 使用管道来处理它的输出.因此,一旦您 Ctrl+C,写入管道会导致脚本块出错,并且不会处理任何进一步的命令.因此,不要使用直接将输出发送到 stdout 的命令,其中有很多是间接使用管道的.另一方面,Write-Host 不使用管道,因此不会抛出错误.

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.

这篇关于使用 Ctrl-C 跳过 Powershell 最后块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆