How to Create a Wait-Anything function with PowerShell

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.

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

Install-Script -Name Wait-Action

Adam Bertram

Chief Automator at Adam the Automator, LLC
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP, 2015 PowerShell hero and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.You can find Adam here on the blog or on Twitter at @adbertram.

Latest posts by Adam Bertram (see all)

Leave a Reply