如何在 PowerShell 中捕获信号? [英] How do I trap signals in PowerShell?

查看:46
本文介绍了如何在 PowerShell 中捕获信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能吗?我终于决定开始设置我的个人 .NET 开发环境,以更接近于我设置 *NIX 开发环境的方式,这意味着要认真学习 Powershell.

Is this possible? I've finally decided to start setting up my personal .NET development environment to closer mimic how I'd set up a *NIX dev environment, which means learning Powershell in earnest.

我目前正在编写一个通过文件系统递归的函数,设置工作目录以便构建东西.困扰我的一件小事是,如果我 Ctrl+C 退出该函数,它会将我留在脚本上次所在的任何位置.我尝试设置一个 trap 块,该块在运行时将目录更改为起点,但这似乎仅用于(和触发)异常.

I'm currently writing a function that recurses through the file system, setting the working directory as it goes in order to build things. One little thing that bothers me is that if I Ctrl+C out of the function, it leaves me wherever the script last was. I've tried setting a trap block that changes the dir to the starting point when run, but this seems to only be intended (and fire) on Exception.

如果这是一种根植于 Unix 的语言,我会为 SIGINT 设置一个信号处理程序,但是我在 Powershell 中找不到任何类似的搜索.戴上我的 .NET 上限,我想我可以将处理程序附加到某种事件,如果我不得不猜测,它将是 $host 的事件,但是我找不到 System.Management.Automation.Internal.Host.InternalHostUserInterface 的任何规范文档,而且我搜索到的任何轶事都没有帮助.

If this were in a language that had root in Unix, I'd set up a signal handler for SIGINT, but I can't find anything similar searching in Powershell. Putting on my .NET cap, I'm imagining there's some sort of event that I can attach a handler to, and if I had to guess, it'd be an event of $host, but I can't find any canonical documentation for System.Management.Automation.Internal.Host.InternalHostUserInterface, and nothing anecdotal that I've been able to search for has been helpful.

也许我遗漏了一些非常明显的东西?

Perhaps I'm missing something completely obvious?

推荐答案

你的意思是这样的吗?

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."

这篇关于如何在 PowerShell 中捕获信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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