Have you ever needed to wait for some other tasks in a script before proceeding to the next? Sure, we have the -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.
$timer.Stop()

## 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.

Install-Script -Name Wait-Action

Join the Jar Tippers on Patreon

It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!

Become a Patron!