Share via


Trapping CTRL+C in Powershell V2

Question

Tuesday, October 26, 2010 4:59 PM

 HI Scripting guys,

Can you please detail on,how I trap ctrl+c key pressed when a script is running,is it a way to make asynchronous calls o the console,so that anytime user presses ctrl+c i can trap that event?

Thanks,

 

Nishant

All replies (3)

Tuesday, October 26, 2010 5:06 PM ✅Answered | 3 votes

A search turned this up: http://www.vistax64.com/powershell/23707-handling-ctrl-c-function.html

It might do what you need.

[console]::TreatControlCAsInput = $true
while ($true)
{
write-host "Processing..."
if ([console]::KeyAvailable)
{
$key = [system.console]::readkey($true)
if (($key.modifiers -band [consolemodifiers]"control") -and
($key.key -eq "C"))
{
"Terminating..."
break
}
}
}

Monday, November 1, 2010 8:57 AM ✅Answered

Hi,

You may start your script as a job.

start-job -scriptblock {. Pathofyourscript.ps1}

Then stop the job if CTRL+C is pressed:

[console]::TreatControlCAsInput = $true
while ($true)
{

 Start-Sleep -s 30

if ([console]::KeyAvailable)
{
$key = [system.console]::readkey($true)
if (($key.modifiers -band [consolemodifiers]"control") -and
($key.key -eq "C"))
{
"Terminating..."

get-job | stop-job

break
}
}
}

For your reference:

about_Jobs
http://technet.microsoft.com/en-us/library/dd315273.aspx

Thanks.

This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click "Mark as Answer" on the post that helps you, and to click "Unmark as Answer" if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.


Tuesday, October 26, 2010 5:17 PM

Thanks for your reply.

Also I wanted to know as my script will be running for 30 minutes,so how i will call this asynchronously so that anytime a ctrl+c key is pressed i trap that,something same like pseventing snappin do for powershell v1.

 

Thanks