Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gracefully stopping in Powershell

How do I catch and handle Ctrl+C in a PowerShell script? I understand that I can do this from a cmdlet in v2 by including an override for the Powershell.Stop() method, but I can't find an analog for use in scripts.

I'm currently performing cleanup via an end block, but I need to perform additional work when the script is canceled (as opposed to run to completion).

like image 300
Justin R. Avatar asked Nov 10 '09 19:11

Justin R.


People also ask

How do I stop a running script in PowerShell?

To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser". Set-ExecutionPolicy RemoteSigned cannot be the first line in your script.

How do I pause a PowerShell script for 10 seconds?

In PowerShell, we can use the Start-Sleep cmdlet to suspend/pause/sleep/wait the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to be completed or pausing before repeating an operation.

How do you Taskkill in PowerShell?

To stop a process by its ID, use taskkill /F /PID <PID> , such as taskkill /F /ID 312 7 if 3127 is the PID of the process that you want to kill. To stop a process by its name, use taskkill /IM <process-name> /F , for example taskkill /ID mspaint.exe /F .


1 Answers

The documentation for try-catch-finally says:

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.

See the following example. Run it and cancel it by pressing ctrl-c.

try {     while($true)     {         "Working.."         Start-Sleep -Seconds 1     } } finally {     write-host "Ended work." } 
like image 63
staale.skaland Avatar answered Sep 27 '22 21:09

staale.skaland