Most of the time when running a PowerShell script or series of commands you want to blast your way through. But there might be times where you want to pause script execution. Perhaps to display an informational message or to simply pace execution. In my work as a trainer and speaker I often use the famous Start-Demo script to walk through demo scripts. But you may not have that function or it doesn't make sense to use in the context of your script. For those situations you can use my Set-Pause function.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
[cc lang="PowerShell"]
Function Set-Pause {
Param(
[Parameter(Position=0)]
[string]$Message="Press any key to continue...",
[ValidateSet("Black","DarkMagenta","DarkRed","DarkBlue",
"DarkGreen","DarkCyan","DarkYellow","Red",
"Blue","Green","Cyan","Magenta","Yellow",
"DarkGray","Gray","White" )]
[string]$ForegroundColor="Green",
[ValidateScript({$_ -gt 0})]
[Alias("seconds")]
[int32]$Sleep,
[Alias("cls")]
[switch]$Clear
)
Write-Host $Message -foregroundcolor $foregroundcolor
#pause for specified number of seconds
if ($Sleep)
{
Start-Sleep -Seconds $sleep
}
else
{
#wait for a key press
$Running=$true
While ($Running)
{
if ($host.ui.RawUi.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
if ($key) {
$Running=$False
}
}
sleep -millisecond 100
} #end While
}
if ($Clear)
{
Clear-Host
}
} #end function
[/cc]
This function uses Write-Host to display a colored message to the console. I take advantage of the foregroundcolor so that the pause prompt, isn't co-mingled with your PowerShell output. You can use same parameter with my function to change the value. The default is Green.
The default pause behavior is to wait for the user to press any key. This is accomplished by checking the KeyAvailable property from the host's RawUI property.
[cc lang="PowerShell"]
if ($host.ui.RawUi.KeyAvailable) {
$key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
if ($key) {
$Running=$False
}
}
[/cc]
As such, this won't work in the ISE and I can't vouch it will work with other PowerShell hosts. Although it will work with the alternative behavior using the -Sleep parameter. With this parameter you can specify a number of seconds to pause, after which time execution continues. The other option is to use -Clear, which will clear the screen after every prompt. Finally, the script file with the function also defines an alias, Pause.
Download Set-Pause.ps1
1 thought on “We Pause a Moment”
Comments are closed.