Press any key to continue……powershell style.

Such a simple thing really, but so handy if you want to pause somewhere in a script to read some sort of output before continuing.

One of the most common ways to pause a script is to use the Read-Host command like this:

1
Read-Host -Prompt "Press enter to continue"

Press enter and you’re good to go.

But, what if you would rather something that lets you just press any key? That’s where you’d think it would get a little more tricky, but actually it’s really simple.

Try this:

1
2
Write-Host "Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

Or, what if you wanted to do a press “(y/n)” prompt?

1
2
3
4
5
6
7
8
9
Write-Host "Do you love powershell? (y/n) "
$key = $Host.UI.RawUI.ReadKey()
if ($key.character -eq "y"){
    Write-Host "Awesome!"
}
 
if ($key.character -eq "n"){
   Write-Host "Booo!"
}

Pretty easy.

I tend to use this a lot when creating “are you sure you want to do this?” scenarios, or if I’m packaging a powershell script into a nice tidy for executable for end users, or tools for our IT department that have some sort of output that needs to be viewed before continuing.

Leave a Reply

Your email address will not be published. Required fields are marked *