等待并重试shell脚本,直到powershell脚本打印特定消息

pftdvrlh  于 2022-11-16  发布在  Shell
关注(0)|答案(1)|浏览(124)

这可能看起来是一个无关紧要的问题,所以请耐心等待。我对这个问题很陌生。
我有一个shell脚本(.sh file),从json文件读取一些配置并运行PowerShell脚本。此PowerShell脚本在Azure VM上安装一些预定义的软件(使用Azure CLI)。之后,它会打印“部署完成”。如果部署因任何原因失败,它会打印“部署失败”。在此过程中,它还会重新启动VM几次,因此它会打印其他调试消息,如“重新启动”、“重新启动成功”等。

我的问题是,如何让shell脚本等待,直到我能够读取“deployment done”消息。如果我看到“deployment failed”消息,我需要重试运行脚本3次(我猜这可以通过循环来实现),然后中止进程。

shell脚本的伪代码

vm_name=`abc`
echo ">> installing software on $vm_name"

az vm run-command invoke --command-id RunPowerShellScript \
-g $rg_name --name $resource_grp \
--scripts script.ps1 \
--parameters "name=$software_name" \
             "ipAddress=$ip_add" \

script.ps1的伪代码

Write-Host ">> installing software"

// try to install
$installResult = Start-process -filepath "// file to software" -Wait -Passthru

if($installResult.ExitCode -eq 0)
{
    Write-Host "<< Rebooting to complete the installation"
} 
elseif($exitResult.ExitCode -ne 0)
{
    Write-Host "<< deployment failed"
}

Restart-Computer -Force
Write-Host "<< Rebooting"
Write-Host "<< deployment done"
xnifntxz

xnifntxz1#

补充一下我的评论,我对shell脚本一无所知,但对使用PowerShell远程处理有一个答案,您可以像这样重写PowerShell脚本,

$failedcounter = 0

Do{ 
Write-Output “Installing Software”

$Install = invoke-command $VM -ScriptBlock {Start-Process <install.exe> -Wait -PassThru }

If($install.exitcode -eq 0){
    Write-Output “Rebooting”
    Restart-Computer $VM -wait -for powershell -Force
    Write-output “Deployment Done”

}Else{
    Write-output “Deployment Failed, retrying” 

$failedcounter++

}

}until(($install.exitcode -eq 0) -or ($failedcounter -eq 3))

相关问题