如何在while循环中运行x次命令- powershell



所以这里我有我的代码的一部分,我试图找出如何我可以运行一个命令内的while循环x次,并结束脚本。

$timer = New-TimeSpan -Minutes 120
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timer) {  
$ReleaseStatus = Invoke-RestMethod -Uri "https://vsrm.dev.azure.com/company/Project/_apis/release/releases/$RId/environments/$EId/?`api-version=6.0" -Method GET -Headers $Header -Verbose
start-sleep -seconds 10
#if release is successful return message and end script. 
if ($ReleaseStatus.Status -eq 'Succeeded') {
write-host "Release Succeeded"
return
}

#if the release fails run the command x number of times. 
if ($ReleaseStatus.status -eq 'Rejected') {
Write-Host "Release failed, Re-running release for you"
#input command here to run release x number of times and then end whole script.
}
}

我尝试了各种方法,但没有得到任何地方,有人知道我怎么能做到这一点吗?

使用一个变量来记录重试次数:

$timer = New-TimeSpan -Minutes 120
# configure number of attempts - this will run up to 5 times (initial attempt + 4 retries)
$retries = 5
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timer -and $retries -gt 0) {
$ReleaseStatus = Invoke-RestMethod -Uri "https://vsrm.dev.azure.com/company/Project/_apis/release/releases/$RId/environments/$EId/?`api-version=6.0" -Method GET -Headers $Header -Verbose
start-sleep -seconds 10
#if release is successful return message and end script. 
if ($ReleaseStatus.Status -eq 'Succeeded') {
write-host "Release Succeeded"
return
}

# release didn't succeed, decrement retry counter
$retries--
if($retries -ge 1){
Write-Host "Release failed, Re-running release for you"
}
else {
Write-Host "Release failed, but no more retries for you"
}
}

现在while()条件只在以下情况下继续:1)我们还没有超时,2)我们还有重试,如果不再满足任何一个条件,它将停止

我是这样做的。请阅读哈希注释

#Check the status of release every y seconds 
$timer = New-TimeSpan -Minutes 120
#set the value of I to 0 outside of the while loop.
$i = 0
$sw = [diagnostics.stopwatch]::StartNew()
while ($sw.elapsed -lt $timer) {  
$ReleaseStatus  = Invoke-RestMethod -Uri "https://vsrm.dev.azure.com/$Organisation/$Project/_apis/release/releases/$RId/environments/$EId/?`api-version=6.0" -Method GET -Headers $Header -Verbose
start-sleep -seconds 10

if ($ReleaseStatus.Status -eq 'Succeeded') {
write-host "Release Succeeded"
return
}
if ($ReleaseStatus.status -eq 'Rejected') {
Write-Host "Release failed, Re-running release for you"
$Uri = "https://vsrm.dev.azure.com/$Organisation/$Project/_apis/Release/releases/$RId/environments/$EId/?api-version=6.0-preview.6"
#we've put the value of retries into a variable to be parametrised. If I is greater than number of retries then return(cancel operation)
if ($i -gt $NumberOfRetryAttempts) {
return
}
Invoke-RestMethod -uri $uri -Method PATCH -Headers $Header -Body $body2 
#you put the I variable inside the while loop and you increment by 1 each time the condition comes back false.
$i++ 
}
}

相关内容

  • 没有找到相关文章

最新更新