2016-05-12 98 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)"   
}