Everyone once in a while I come across a PowerShell script that behaves like an old-fashioned batch file. Not that there's anything wrong with that, but often these types of scripts put in a pause at the end of script so you can see that it finished. You might have seen a command like this in a PowerShell script.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
cmd /c pause
Sure, it works but is hardly elegant PowerShell. First, I'm not sure you even need it. If you want to draw attention to the fact that your script ended, consider using Write-Host with a foreground (or background color).
Write-Host "Press any key to continue . . ." -foregroundcolor yellow
But if you truly need the user to acknowledge that the script has finished you can use Read-Host.
Read-Host "Press any key to continue . . ." | Out-Null
I'm piping the command to Out-Null because I don't care what the user enters, only that they hit a key.
If you prefer a move visual cue, you can always resort to the Wscript.Shell COM object.
$ws = new-object -ComObject wscript.shell $ws.Popup("Press any key to continue . . .",0,"Script Finished",0+64) | Out-Null
The popup will remain until the user clicks OK. Or you can change the second parameter from 0 to another value to have the popup automatically dismiss after the specified number of seconds.
So if you need a refreshing pause, there are plenty of PowerShell options for you to use.
UPDATE:
After someone posted a comment I realized there is yet another way to do this. Add these two lines to the end of your PowerShell script.
write-host `n"Press any key to continue . . ." -NoNewline -ForegroundColor Green $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown,IncludeKeyUp") | out-null
This is very similar behavior to Read-Host but with a bit more flexibility.
With “Read-Host”, though, wouldn’t that not actually dismiss until you hit enter? So, “Press Enter to continue…”?
You’re right. To be clear you whould change the text which I assumed people would anyway. I was merely re-using the same text.
Why is Write-Host so verboten in the PowerShell community but Read-Host is acceptable?
Because people use Write-Host instead of writing to the pipeline. Read-Host is completely different.
We started to use the ReadKey method (without the IncludeKeyUp option) until we found out that switching windows using alt-tab can cause this to trigger – even though you’re not ready for it. We switched to reading the value and making sure it complies with that we’re looking for in a do while loop. I’ll need to try adding the IncludeKeyUp to see if that makes a difference.
Interesting. I have not run into that situation. Thanks for sharing.
Powershell 3.0 has the “Pause” command.
Why yes it does and the code is essentially the same as mine in terms of using Read-Host. My approach has a few more bells if you need them. But thanks for pointing this out.