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

Leave a Reply