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.
By day, I’m a systems admin for a medium size company in the Pacific Northwest.
By night, I’m a blogger, gamer, and all around general nerd.
If you found one of my articles useful, please consider supporting this site!
Monero: 48PxwMvbwoB2M86sHespLBKcSL9cWxrnJDmga9XshSqRP1joykRNpKkDGUz4ohhxD1bMH92poMyZWBBqkPmQ2bHpLP4EDnz
Bitcoin: bc1qc0fyze8x9lxp42x5p3zpry6f0lsr6l5pgq4jkh
Ethereum: 0xc613cBc79Ea4a84AE5538ec3321E214363305121