PoshCode Archive  Artifact [97d1d8f3f2]

Artifact 97d1d8f3f20b6e4b4731793b53f9ee0d9aeceb73c2844a7630665266c5bd605a:

  • File WhileTimeout.ps1 — part of check-in [572b4af9bd] at 2018-06-10 14:07:52 on branch trunk — Generic wrapper for the While statement that will execute a condition a given number of max tries, waiting a given number of seconds in between. (user: unknown size: 1061)

# encoding: ascii
# api: powershell
# title: WhileTimeout
# description: Generic wrapper for the While statement that will execute a condition a given number of max tries, waiting a given number of seconds in between.
# version: 0.1
# type: function
# license: CC0
# x-poshcode-id: 609
# x-archived: 2008-09-29T01:24:59
#
# This example will execute the “IsItDoneYet” function (that checks a hypothetical external factor) once every 5 seconds, a total of no more than 24 times, which will take approximately two minutes, not including function execution time.
# > $condition = { IsItDoneYet }
# > WhileTimeout 5 24 $condition
#
function WhileTimeout ( [int]$interval, [int]$maxTries, [scriptblock]$condition )
{
	$i = 0
	$startTime = Get-Date
	while ( &$condition ) {
		$i++
		if ( $i -lt $maxTries ) {
			Start-Sleep -seconds $interval
		} else {
			Throw "Operation exceeded timeout"
		}
	}
	$endTime = Get-Date
	$duration = ( $endTime - $startTime ).TotalSeconds
	Write-Verbose "Operation elapsed time: $duration seconds"
}