| by Arround The Web | No comments

How to Pause a PowerShell Script

PowerShell is a scripting tool used to perform Windows automation and administrative tasks. It also offers a feature of pausing a script. PowerShell scripts are paused to add a user input, wait for another process to execute, or slow down the execution speed. PowerShell script execution can be paused using specific commands.

This write-up will walk us through various methods to fix the mentioned query.

How to Pause a Script in PowerShell?

These are the methods that can be applied to pause a script:

Method 1: Use the “Pause” Cmdlet to Pause a PowerShell Script

The “pause” cmdlet is utilized in PowerShell to add a pause in a script. When the “pause” cmdlet gets executed it displays the dialog “Press any key to continue. . .” when no string input is given.

Example

This example will demonstrate the working of the “pause” cmdlet:

> write-host "Hello World"
> cmd /c 'pause'

 
In this stated example:

    • First, we added a string with the help “Write-Host” command.
    • After that, we added the “cmd /c ‘pause’” cmdlet to pause the script:

 

As can be seen, the “pause” cmdlet successfully added a pause in the script.

Method 2: Use the “Read-Host” Command to Pause a PowerShell Script

Another method is a “Read-Host” to pause a script. This cmdlet prompts for user input and waits until the input is given.

Example

Now, pause the script using the “Read-Host” cmdlet as follows:

> Read-Host "Press any key to continue"

 

Method 3: Use the “Timeout” Command to Pause a PowerShell Script

The “timeout” command pauses the script for a specified number of seconds. It is useful when you want the user to wait for the process to execute properly.

Example

In this given demonstration, the “timeout” cmdlet will be used to pause a script for “5” seconds:

> write-host "Script is paused for 5 seconds"
> timeout /t 5

 

Method 4: Use the “Start-Sleep” to Pause the Script

Another command that is used most commonly is the “Start-Sleep”. It pauses the script for a specified period of time.

Example

Now, we will utilize the “Start-Sleep” cmdlet to pause a script for five seconds:

> write-host "Script will remain paused for 5 seconds"
> Start-Sleep -Seconds 5

 

That was all about pausing PowerShell script.

Conclusion

A PowerShell script can be paused using various methods. These methods include “Pause”, “Read-Host”, “Timeout”, or “Start-Sleep” cmdlets. In order to pause a script, add any of these mentioned commands in the script body. This article has provided in-depth detail to pause a script in PowerShell.

Share Button

Source: linuxhint.com

Leave a Reply