August 16, 2012

How to do a PAUSE

In the good old days, with cmd.exe batchs you can easily add a PAUSE in your script to allow you press a key to continue.

In Powershell you have to use the ReadKey() method. The only bug is that you can’t use ReadKey() if your not in the console. That could be a problem if you use PowerGUI or PowerShellISE to develop and run your scripts.

Here’s a little function that will do the trick :

#.SYNOPSIS 
# Emulation of PAUSE command (cmd)
#.DESCRIPTION
# Author : Jeffrey Snover [MSFT]
#.LINK
# http://blogs.msdn.com/b/powershell/archive/2007/02/25/pause.aspx
function Pause ([string]$Message="[Pause] Press Enter key to continue ...")
{
	if (((Get-Host).Name) -eq 'ConsoleHost') {
		Write-Host -NoNewLine $Message
		$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
		Write-Host ""
	}
	Else {
	Read-Host -Prompt $message
	}
}

Thanks to Jeffrey Snover for this code.

No comments:

Post a Comment