Forum Discussion

JoergDebus's avatar
JoergDebus
Copper Contributor
Mar 05, 2024

How to handle a CTRL-C input from the console as an event like a SIGINT in other languages?

I have to stop a long running script by an external event like entering CTRL-C at the console and then to process some cleanup actions before exiting. I have tried this but it terminates silently after a CTRL-C.

 

 

 

function OnExit {
    Write-Host "You pressed Ctrl+C!"
}

Register-EngineEvent PowerShell.Exiting -Action { OnExit } -SupportEvent

try {
    while ($true) {
        'Do something ...'
        Start-Sleep -Seconds 1
    }
}
catch {
    if ($_.Exception -is [System.Management.Automation.PipelineStoppedException]) {
        # This block will not execute on CTRL-C
    }
finally {
    'In finally now'
    }
}

 

 

 

 Tia for any advice.

Jörg

  • JoergDebus I used this in one of my scripts. This is for using Escape to stop.

     

     

    while ( $true ) {
        if ($host.ui.RawUi.KeyAvailable) {
            $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp,IncludeKeyDown")
            if ($key.VirtualKeyCode -eq 27 ) { 
                Write-Host ("Stopped") -ForegroundColor Green
                return
            }
        }
    }

     



    Please click Mark as Best Response & Like if my post helped you to solve your issue.
    This will help others to find the correct solution easily. It also closes the item.

    If one of the posts was helpful in other ways, please consider giving it a Like.

    • JoergDebus's avatar
      JoergDebus
      Copper Contributor
      Hi Harm.
      thanx for your tip.
      Catching a key is a good approach. My problem is, that I have long running functions which should be interrupted. Polling during an outer loop like you scribbled it, does not handle this.
      Best regards
      Jörg

Resources