PWRSHELL.COM


Powershell all the Things!

| HOME | ABOUT | BLOG | GITHUB | TWITTER |

Want to learn powershell? Get Powershell in a Month of Lunches

PRESS ANY KEY TO CONTINUE


Published: 2022-4-6

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:
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:
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?
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.

Share this page: Reddit | Twitter | Facebook

Copyright 2022 - pwrshell.com
~ Hand coded with organic home grown PHP and ♥ ~
chris(at)pwrshell.com