Forum Discussion
JoergDebus
Mar 05, 2024Copper Contributor
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 aft...
Mar 06, 2024
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.
- JoergDebusMar 09, 2024Copper ContributorHi 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