How to Create Powershell Wait – Anything Function

Adam Bertram

Adam Bertram

Read more posts by this author.

Have you ever needed to wait for some other tasks in a script before proceeding to the next? Sure, we have the Powershell Wait parameter on a lot of commands but not everything that we’re willing to come across will be that easy. In order to prevent me from reinventing the wheel every time, I decided to create a generic Wait function that would wait on anything.

When it comes down to it, a wait task only has three components:

  • Conditional code to execute to determine when to continue.
  • Conditional code to return $true or $false representing to continue waiting or not.
  • A timeout to ensure the code doesn’t wait indefinitely.

We can build a tool that incorporates these three components with a scriptblock that returns a boolean value (`$true` or $false), a while loop to continually execute this scriptblock and a timer to track how long this process is taking to timeout if necessary.

Here’s an example of how to build it.

$Timeout = 10 ## seconds
$jobs = Get-Job
$Condition = {param($jobs) 'Running' -not in $jobs.State }
$ConditionArgs = $jobs
$RetryInterval = 5 ## seconds

## Start the timer
$timer = [Diagnostics.Stopwatch]::StartNew()

## Start checking the condition scriptblock. Do this as long as the action hasn't exceeded
## the timeout or the condition scriptblock returns something other than $false or $null.
while (($timer.Elapsed.TotalSeconds -lt $Timeout) -and (& $Condition $ConditionArgs)) {

    ## Wait a specific interval
    Start-Sleep -Seconds $RetryInterval

    ## Check the time
    $totalSecs = [math]::Round($timer.Elapsed.TotalSeconds,0)
    Write-Verbose -Message "Still waiting for action to complete after [$totalSecs] seconds..."

## The action either completed or timed out. Stop the timer.

## Return status of what happened
if ($timer.Elapsed.TotalSeconds -gt $Timeout) {
    throw 'Action did not complete before timeout period.'
} else {
    Write-Verbose -Message 'Action completed before timeout period.'

An implementation of this is in the PowerShell Gallery so feel free to take it for a test drive of this Powershell wait command.

Install-Script -Name Wait-Action

Subscribe to Adam the Automator

Get the latest posts delivered right to your inbox

Looks like you're offline!