在powershell脚本中使用时间进行条件循环

时间:2016-05-12 16:36:59

标签: powershell azure timer system

这是我的代码:

        #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中记录它。

1 个答案:

答案 0 :(得分: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)"        
}