Pause PowerShell with Start-Sleep Command The most popular command to pause in PowerShell is the Start-Sleep command or cmdlet. Also, the Start-Sleep command is the official and native command provided by PowerShell.
The pause command is very simple, and will display Press any key to continue . . . and remain that way until a key is pressed to resume execution. You may ask how to use this in a script, but just like you would any other command, insert the cmd /c 'pause' command within your script to utilize the native functionality.
Using the PowerShell Start Sleep cmdlet You can also write Start-Sleep 5 to let the script sleep for 5 seconds.
I think it is worthwhile to recap/summarize the choices here for clarity... then offer a new variation that I believe provides the best utility.
write-host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
cmd /c Pause | Out-Null
Read-Host -Prompt "Press Enter to continue"
This is a composite of <1> above with the ISE workaround/kludge extracted from the proposal on Adam's Tech Blog (courtesy of Nick from earlier comments on this page). I made two slight improvements to the latter: added Test-Path to avoid an error if you use Set-StrictMode (you do, don't you?!) and the final Write-Host to add a newline after your keystroke to put the prompt in the right place.
Function Pause ($Message = "Press any key to continue . . . ") {
if ((Test-Path variable:psISE) -and $psISE) {
$Shell = New-Object -ComObject "WScript.Shell"
$Button = $Shell.Popup("Click OK to continue.", 0, "Script Paused", 0)
}
else {
Write-Host -NoNewline $Message
[void][System.Console]::ReadKey($true)
Write-Host
}
}
cmd /c pause | out-null
(It is not the PowerShell way, but it's so much more elegant.)
Save trees. Use one-liners.
I assume that you want to read input from the console. If so, use Read-Host
.
The solutions like cmd /c pause
cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.
The solutions using Read-Host
force the user to press Enter and are not really "any key".
This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause
command.
Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
In addition to Michael Sorens' answer:
Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With