Shell脚本等待PowerShell输出指定消息并失败重试3次的实现方法
实现Shell脚本等待部署完成+失败自动重试3次
问题场景
通过Shell脚本调用Azure CLI执行VM上的PowerShell部署脚本,部署过程中VM会多次重启,PS脚本成功时输出<< deployment done,失败时输出<< deployment failed,需要Shell脚本:
- 持续等待直到捕获到成功消息
- 若捕获到失败消息,自动重试最多3次后终止
一、修正PowerShell部署脚本(script.ps1)
原PS脚本存在逻辑缺陷:Restart-Computer -Force会直接中断脚本,导致后续的成功消息无法输出;同时存在未定义变量$exitResult。修正后的脚本通过计划任务实现重启后的后续步骤:
Write-Host ">> installing software" # 执行软件安装 $installResult = Start-Process -FilePath "你的软件安装路径" -Wait -PassThru if ($installResult.ExitCode -eq 0) { Write-Host "<< Rebooting to complete the installation" Write-Host "<< rebooting" # 创建开机启动任务,重启后完成部署收尾 $scriptPath = $MyInvocation.MyCommand.Path $trigger = New-ScheduledTaskTrigger -AtStartup $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File `"$scriptPath`" -PostReboot" Register-ScheduledTask -TaskName "PostDeploymentReboot" -Trigger $trigger -Action $action -Force | Out-Null # 执行重启 Restart-Computer -Force } else { # 输出失败信息并返回非0退出码 Write-Host "<< deployment failed" exit 1 } # 处理重启后的收尾逻辑 if ($args[0] -eq "-PostReboot") { Write-Host "<< rebooted successfully" # 可在此添加部署完成后的确认步骤 Write-Host "<< deployment done" # 删除临时计划任务 Unregister-ScheduledTask -TaskName "PostDeploymentReboot" -Confirm:$false exit 0 }
二、修改Shell脚本实现等待与重试逻辑
Shell脚本需要循环执行部署命令,检查输出内容并处理重试:
vm_name="abc" rg_name="你的资源组名称" software_name="目标软件名称" ip_add="VM的IP地址" max_retries=3 retry_count=0 echo ">> installing software on $vm_name" while [ $retry_count -lt $max_retries ]; do # 调用Azure CLI执行PowerShell脚本,捕获输出 az_output=$(az vm run-command invoke \ --command-id RunPowerShellScript \ -g "$rg_name" \ --name "$vm_name" \ --scripts @script.ps1 \ --parameters "name=$software_name" "ipAddress=$ip_add") # 检查是否部署成功 if echo "$az_output" | grep -q "<< deployment done"; then echo ">> Deployment succeeded on $vm_name" exit 0 fi # 检查是否部署失败 if echo "$az_output" | grep -q "<< deployment failed"; then retry_count=$((retry_count + 1)) echo ">> Deployment failed, retrying ($retry_count/$max_retries)..." sleep 30 # 重试前等待30秒 continue fi # 检查是否正在重启,等待后重新检查 if echo "$az_output" | grep -q "<< rebooting"; then echo ">> VM is rebooting, waiting 5 minutes for completion..." sleep 300 # 等待5分钟让VM重启完成 continue fi # 其他异常情况,执行重试 retry_count=$((retry_count + 1)) echo ">> Unexpected output, retrying ($retry_count/$max_retries)..." sleep 30 done # 重试次数耗尽,终止进程 echo ">> Deployment failed after $max_retries retries, terminating." exit 1
关键说明
- PS脚本核心修正:通过计划任务在VM重启后自动执行收尾步骤,确保成功消息能正常输出;添加退出码方便Shell脚本判断执行状态。
- Shell脚本核心逻辑:设置最大重试次数,每次执行后解析输出,针对成功、失败、重启三种场景分别处理,失败时自动重试,成功则立即退出。
内容的提问来源于stack exchange,提问作者user-x
相关产品推荐
相关产品推荐

