How to cancel wait-event by Ctrl-C instead of cancelling whole script in powershell -


i using event related command in powershell, , when register object event , wait it, script paused wait-event call.

based on documentation,

the wait-event cmdlet suspends execution of script or  function until particular event raised. execution  resumes when event detected.  cancel wait, press ctrl+c. 

but found is, when press ctrl-c in powershell console, whole script ended instead of wait-event call, thought wait-event call maybe return $null value.

i don't know if wrong in understanding, hope share more idea on it.

$port = new-object system.io.ports.serialport com5,115200,none,8,one $port.open() $subscription = register-objectevent -inputobject $port -eventname datareceived -sourceidentifier "datareceived" while($true) {     $event = wait-event -sourceidentifier "datareceived"     #     # how can check if user press control-c cancel wait-event     #     [system.io.ports.serialport]$sp = $event.sender;     $line = $sp.readexisting();     write-host $event.eventidentifier;     write-host $line;      remove-event -eventidentifier $event.eventidentifier; }  unregister-event -sourceidentifier "datareceived" $port.close() 

--edit---

thanks answer, want point out known solution tried.

[console]::treatcontrolcasinput = $true if ([console]::keyavailable) {     $key = [system.console]::readkey($true)     if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "c"))     {       "terminating..."       break     } } 

this way resolve common control-c scenario, problem application paused wait-event call, have no change check key input.

especially, when enable ctrl c console via [console]::treatcontrolcasinput = $true, control-c not able cancel wait-event more, problem here.

here example, can try ( rewrite usable 1 testing ):

$timer = new-object system.timers.timer  [console]::treatcontrolcasinput = $true;  $subscription = register-objectevent -inputobject $timer -eventname elapsed -sourceidentifier "timeelapsed" $event = wait-event -sourceidentifier "datareceived" write-host "user cancelled" unregister-event -subscriptionid $subscription.id 

you can run script, , without [console]::.... test.

you might have call [console]::treatcontrolcasinput = $true tell that (ctrl+c) treated ordinary input , use statements in loop:

if ([console]::keyavailable) {     $key = [system.console]::readkey($true)     if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "c"))     {       "terminating..."       break     } } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -