Reputation: 312
How can I stop Powershell by pressing a key. I have a loop, which should be stopped, when I press "q". How to do that.
I have found the following code, but didn't work
while($true) {
Write-Host "Working" -BackgroundColor Green
if($Host.UI.RawUI.KeyAvailable -and ("q" -eq $Host.UI.RawUI.ReadKey("IncludeKeyup,NoEcho").Character)) {
Write-Host "Exiting now, don't try to stop me...." -BackgroundColor DarkRed
break;
}
}
Anyone got an idea?
Upvotes: 1
Views: 1775
Reputation: 312
the same code works, but not in PowerShell ISE but in the normal PowerShell console. You guys have to save it if you are scripting and then execute via Powershell console.
Upvotes: 1
Reputation: 151
If you want to exit the program itself you could use Ctrl+C
and it will stop the script.
You could be more specific, that if you have some code to run after the loop, in that case this wont work.
Upvotes: 1