How do I trap signals in PowerShell?
powershell
Solution
Do you mean something like this?
try
{
Push-Location
Set-Location "blah"
# Do some stuff here
}
finally
{
Pop-Location
}
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."
Problem
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. 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. 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?