I think it's worth demonstrating the choice here for clarity ... then suggest a new option that, in my opinion, provides better utility.
<1> ReadKey (System.Console)
write-host "Press any key to continue..." [void][System.Console]::ReadKey($true)
- Advantage: accepts any key, but correctly excludes the modifier keys Shift, Alt, Ctrl.
- Disadvantage: does not work in PS-ISE.
<2> ReadKey (RawUI)
Write-Host "Press any key to continue ..." $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
- Disadvantage: does not work in PS-ISE.
- Disadvantage: does not exclude modifier keys.
<3> cmd
cmd /c Pause | Out-Null
- Disadvantage: does not work in PS-ISE.
- Disadvantage: Apparently launches a new shell / window on first use; not noticeable on subsequent use, but still has overhead
<4> Read-Host
Read-Host -Prompt "Press Enter to continue"
- Advantage: Works in PS-ISE.
- Shortcoming: accepts only the Enter key.
<5> ReadKey composite
This is a composition above 1 using the ISE / kludge workaround extracted from the Adam Tech Blog offer (kindly provided by Nick from the previous comments on this subject page). I made two small improvements for the latter: a test path was added to avoid error if you use Set-StrictMode (right?), And final Write-Host to add a new line after pressing a key to place 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 } }
- Advantage: accepts any key, but correctly excludes the modifier keys Shift, Alt, Ctrl.
- Advantage: works in PS-ISE (although only with Enter or mouse)
- Disadvantage: more than one ship!
Michael Sorens Mar 12 '14 at 20:17 2014-03-12 20:17
source share