Take the 2-minute tour ×

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?

share|improve this question

2 Answers 2

up vote 8 down vote accepted

Do you mean something like this?

    Set-Location "blah"
    # Do some stuff here


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

share|improve this answer
Finally a straight-forward solution to clean up a CTRL-C terminated Job (: –  Callahan Aug 19 '13 at 12:50

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..."
share|improve this answer
Doesn't work from the ISE, but perfect in a normal PowerShell window –  Froosh Apr 29 at 2:53

Your Answer


