Home > PowerShell > Function: New-Pause – Pausing PowerShell Scripts

Function: New-Pause – Pausing PowerShell Scripts

Yesterday, I wrote about a sleep function to cause a predetermined delay in a script. Today, I give you a short function, New-Pause. New-Pause stops a script and waits for the user to press a key before continuing.

function New-Pause {
 Write-Host "Press any key to continue" -ForegroundColor green
 $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
} # end function New-Pause

We can add some flexibility into it by allowing for the function to be called with alternative values for the text color and the text itself.

function New-Pause {
  [CmdletBinding(SupportsShouldProcess, SupportsPaging, HelpUri = 'https://ucunleashed.com/885')]
  param(
    # Text that is displayed as the prompt when paused.
    [Parameter(ValueFromPipelineByPropertyName)]
    [ValidateNotNullOrEmpty()]
    $PausePrompt = 'Press any key to continue',
    
    # Color of the prompt.
    [Parameter(ValueFromPipelineByPropertyName)]
    [ValidateNotNullOrEmpty()]
    [ValidateSet('Black', 'DarkMagenta', 'DarkRed', 'DarkBlue', 'DarkGreen', 'DarkCyan', 'DarkYellow', 'Red', 'Blue', 'Green', 'Cyan', 'Magenta', 'Yellow', 'DarkGray', 'Gray', 'White')]
    $PauseColor = 'Green'
  )
  Write-Host $PausePrompt -ForegroundColor $PauseColor
  $null = $host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
  Write-Host 'Continuing...'
} # end function New-Pause

Call the function using

New-Pause
New-Pause

New-Pause

Once any key is pressed, your script can continue.

Donations

I’ve never been one to really solicit donations for my work. My offerings are created because *I* need to solve a problem, and once I do, it makes sense to offer the results of my work to the public. I mean, let’s face it: I can’t be the only one with that particular issue, right? Quite often, to my surprise, I’m asked why I don’t have a “donate” button so people can donate a few bucks. I’ve never really put much thought into it. But those inquiries are coming more often now, so I’m yielding to them. If you’d like to donate, you can send a few bucks via PayPal at https://www.paypal.me/PatRichard. Money collected from that will go to the costs of my website (hosting and domain names), as well as to my home lab.

Categories: PowerShell Tags: ,