且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 PowerShell 中捕获信号?

更新时间:2021-09-26 08:27:46

你的意思是这样的吗?

try
{
    Push-Location
    Set-Location "blah"
    # Do some stuff here
}

finally
{
    Pop-Location
}

请参阅文档此处.特别是该段落:无论 Try 块是否遇到终止错误,Finally 块语句都会运行.Windows PowerShell 在脚本终止之前或当前块超出范围之前运行 finally 块.即使您使用 CTRL+C 停止运行,Finally 块也会运行脚本.如果 Exit 关键字从 Catch 块中停止脚本,则 finally 块也会运行."

See documentation here. Particularly that paragraph: "The Finally block statements run regardless of whether the Try block encounters a terminating error. Windows PowerShell runs the Finally block before the script terminates or before the current block goes out of scope. 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."