PowerShell Scripting Pause and Wait Commands Explained
PowerShell Scripting Pause and Wait Commands Explained

Many of you are familiar with the “timeout” command used in Windows Batch scripts to pause/wait/sleep the script for a specific amount of time. In PowerShell, the equivalent command is the Start-Sleep cmdlet, which allows you to suspend/pause/sleep/wait the activity in a script or session for a specified duration. This cmdlet can be handy for various tasks, such as waiting for an operation to complete or pausing before repeating an action.

To pause a PowerShell script for 5 seconds, use the following command:

powershell
Start-Sleep -Seconds 5

Alternatively, you can use the -Milliseconds parameter to specify the duration in milliseconds:

powershell
Start-Sleep -Milliseconds 25

For convenience, aliases like -s and -ms can be used instead of the full parameter names. For more details about the Start-Sleep cmdlet, refer to the Microsoft Docs.

Another useful cmdlet is Read-Host, which pauses the script until the user provides input. This is particularly useful for pausing a PowerShell script until a key press, for example:

powershell
Read-Host -Prompt "Press any key to continue..."

Read-Host is typically used to get user input, which can then be reused in the script:

powershell
$InputFromUser = Read-Host -Prompt "Get me some input..."

For more information about the Read-Host cmdlet, check out Microsoft Docs.

It’s worth noting that avoiding unnecessary pauses in a script is generally a good practice.

I hope this quick PowerShell guide gives you an overview of how to add a sleep/wait/pause in a PowerShell script. If you have any questions, feel free to leave a comment. For more information on installing and updating to PowerShell 7, check out my blog post. You can also learn about the new features in PowerShell 7 and PowerShell remoting between Windows, Linux, and macOS using PowerShell remoting over SSH.

Leave a Reply

Your email address will not be published. Required fields are marked *