# 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" }