Bandit
Bandit

Reputation: 523

Powershell - Do while

I have a little question regarding my do while script Right now when $BackuptoPM -eq 'rejected' I got the message tat upload failed and afterward I get the message that the upload completed. upload completed should be only when the loop is ended. How can I fix this that when the script failed I will get only the right message?

do {
                $p = Get-VSTeamRelease -id $ReleaseID
                $BackuptoPM = $p.environments[0].status 
                $BackuptoALM = $p.environments[1].status 
                $time = Get-Date -UFormat "%d/%m/%Y %R:%S"
                write-host "Upload to PM is in progress...$time"
                Start-Sleep -Seconds 60
                if ($BackuptoPM -eq 'rejected') {
                    write-host "Upload to PM failed" -ForegroundColor Red
                    break
                }
            }
            while ($BackuptoPM -ne 'succeeded' -and $BackuptoALM -ne 'rejected')

            write-host
            write-host "Upload to PM is completed" -ForegroundColor Green
            write-host 

Upvotes: 0

Views: 65

Answers (1)

Theo
Theo

Reputation: 61068

Your logic is a bit strange here.. Inside the loop, you break out if $BackuptoPM -eq 'rejected' and then write "Upload to PM is completed", no matter what happened..

I would rather create a loop where you set a maximum number of tries, and afterwards report on what went wrong or not.

Something like this perhaps:

# as example try 3 times
for ($i = 0; $i -lt 3; $i++) {   
    $time = Get-Date -UFormat "%d/%m/%Y %R:%S"
    Write-Host "Upload to PM is in progress...$time"
    $p = Get-VSTeamRelease -id $ReleaseID
    $BackuptoPM  = $p.environments[0].status 
    $BackuptoALM = $p.environments[1].status 
    # break if both succeeded
    if ($BackuptoPM -eq 'succeeded' -and $BackuptoALM -ne 'rejected') {
        break
    }
    Start-Sleep -Seconds 60
}

# now test what happened
if ($BackuptoPM -eq 'succeeded' -and $BackuptoALM -ne 'rejected') {
    Write-Host "Upload to PM is completed" -ForegroundColor Green
}
elseif ($BackuptoPM -ne 'succeeded') {
    Write-Host "Upload to PM failed" -ForegroundColor Red
}
else {
    Write-Host "Upload to ALM failed" -ForegroundColor Red
}

Of course, you can also use a while loop and have it run for a maximum time period like for instance 1 hour

$refDate = (Get-Date).AddHours(1)
while ((Get-Date) -lt $refDate){
    $time = Get-Date -UFormat "%d/%m/%Y %R:%S"
    Write-Host "Upload to PM is in progress...$time"
    $p = Get-VSTeamRelease -id $ReleaseID
    $BackuptoPM  = $p.environments[0].status 
    $BackuptoALM = $p.environments[1].status 
    # break if both succeeded
    if ($BackuptoPM -eq 'succeeded' -and $BackuptoALM -ne 'rejected') {
        break
    }
    Start-Sleep -Seconds 60
}

Upvotes: 2

Related Questions