2016-05-12 60 views
1

這裏是我的代碼:在PowerShell腳本中使用時間條件循環

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

我想提出一個條件,while循環,如果它已經運行了可以說2小時,然後就應該退出。似乎無法找到如何啓動計時器並在PowerShell中保存記錄。

+0

您應該看看使用'stopwatch'並通過'&&'在'while'循環中添加附加條件。 – gravity

回答

1

在這個例子中,我所做的只是在While循環之前添加一行,以確保在While循環期間2小時還沒有通過。

根據您希望break何時退出流程,這可能是最好的選擇,因爲一旦您打滿整整2個小時,它就不會再次啓動新的循環,並且循環將被定爲重新開始。

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