Quantcast
Channel: Gav's Blog – SharePoint .NET & Tech
Viewing all articles
Browse latest Browse all 41

PowerShell: Pause for specific key strokes

$
0
0

Today I needed to add a wait into a Powershell script, given that is a point where the user running the script needs to go do some manual steps on another server I thought it might be a good idea to wait for a specific key press. So off to Bing I go…

There are plenty of great articles on waiting for or getting user input, personally I really like Windows PowerShell Tip of the Week: Pausing a Script Until the User Presses a Key and the User Interaction chapter from the PowerShell Cookbook. After seeing that [Console]::ReadKey() would give me an object which told me about the modifers on the key press (Crtl, Alt and/or Shift) I started thinking about making that key press more specific, say Ctrl + G, so I wrote a function to handle this:

function Pause
{
	param([string] $pauseKey,
			[ConsoleModifiers] $modifier,
			[string] $prompt,
			[bool] $hideKeysStrokes)
			
    Write-Host -NoNewLine "Press $prompt to continue . . . "
    do
	{
		$key = [Console]::ReadKey($hideKeysStrokes)
	} 
	while(($key.Key -ne $pauseKey) -or ($key.Modifiers -ne $modifer))	
	
    Write-Host
}

This function received a bit of inspiration from How to Properly Pause a PowerShell Script which itself is pretty interesting.

Things to note:

Ctrl + C will still cancel the script, you’ll need to use $host.UI.RawUI.ReadKey with the AllowCtrlC option to prevent that, but then accessing the Modifiers is done differently.

$modifers is a simple enum value of ConsoleModifiers if you want to do combinations like Atl+Shift you’ll pass a collection of modifers and do –band operations to see if your conditions are met.

To call the Pause function use something like this:

$modifer = [ConsoleModifiers]::Control
Pause "G" $modifer "Ctrl + G" $true  

And then you’ll see this: image


Filed under: Uncategorized

Viewing all articles
Browse latest Browse all 41

Trending Articles