Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trap signals in PowerShell?

Tags:

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.

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?

like image 488
Marc Bollinger Avatar asked Apr 16 '12 17:04

Marc Bollinger


2 Answers

This handles console kepboard input. If control C is pressed during the loop you'll have a chance to handle the event however you want. In the example code a warning is printed and the loop is exited.

[console]::TreatControlCAsInput = $true
dir -Recurse -Path C:\ | % {
    # Process file system object here...
    Write-Host $_.FullName

    # Check if ctrl+C was pressed and quit if so.
    if ([console]::KeyAvailable) {
        $key = [system.console]::readkey($true)
        if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "C")) {
            Write-Warning "Quitting, user pressed control C..."
            break
        }
    }
like image 50
Andy Arismendi Avatar answered Sep 19 '22 12:09

Andy Arismendi


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

like image 24
David Brabant Avatar answered Sep 20 '22 12:09

David Brabant