chillax786
chillax786

Reputation: 369

Using time in a powershell script for conditional loop

Here is my code:

        #make sure deployment is in running state
$deployment = Get-AzureDeployment -servicename $_serviceName -slot $_slotName
Write-Host "$_serviceName is in state $($deployment.status)"
while ($deployment.Status -ne "running")
{   
    Write-Host "wait 5 seconds before trying again" 
    Start-Sleep -s 5
    $deployment = Get-AzureDeployment -servicename $_serviceName -slot $_slotName
    Write-Host "$_serviceName is in state $($deployment.status)"        
}

I want to put a condition in the while loop that if it's been running for lets say 2 hours, then it should exit. Can't seem to find out how to start a timer and keep a record of it in powershell.

Upvotes: 1

Views: 167

Answers (1)

gravity
gravity

Reputation: 2066

In this example, all I did was add a line to before your While loop, that also checks to make sure 2 hours have not yet passed during the While loop.

Depending on when you'd want to break out of the process, this may be the best option as it won't start a new loop again as soon as you hit a full 2 hours, and the loop is slated to restart.

#make sure deployment is in running state
$deployment = Get-AzureDeployment -servicename $_serviceName -slot $_slotName
Write-Host "$_serviceName is in state $($deployment.status)"
$StopWatch = [System.Diagnostics.Stopwatch]::StartNew() #new code
while (($deployment.Status -ne "running") -and ($StopWatch.Elapsed.Hours -lt 2)) #new code
{   
    Write-Host "wait 5 seconds before trying again" 
    Start-Sleep -s 5
    $deployment = Get-AzureDeployment -servicename $_serviceName -slot $_slotName
    Write-Host "$_serviceName is in state $($deployment.status)"        
}

Upvotes: 1

Related Questions