如何在PowerShell中捕获Azure CLI的Blob存在检测结果以实现上传重试
问题
我有一套通常可靠但在某台服务器上存在异常的Azure Blob Storage自动备份流程。我希望通过PowerShell脚本在上传失败时进行重试,因此需要编写if语句(或do-while循环),在文件尚未存在于ABS(Azure Blob Storage)中时执行对应操作。请问如何捕获Azure CLI命令az storage blob exists的执行结果?
我的测试代码如下:
if(az storage blob exists --account-name test --container-name test --name $name --sas-token $sasToken){ Echo "This is true" } else{ Echo "This is false" }
单独运行该Azure CLI命令的输出为:
{ "exists": true }
我近期使用多种编程语言,容易混淆语法。
解决方案
在PowerShell中,直接用if(az ...)判断的是命令的退出码(执行成功则退出码为0,会进入true分支),而非命令输出JSON里的exists值,所以你的测试代码不管Blob是否存在都会输出"This is true"。要正确捕获结果,需把CLI输出的JSON转换成PowerShell对象,再提取exists属性:
1. 基础判断写法
先捕获命令输出并转为对象,再基于exists属性判断:
# 捕获CLI输出并转换为PowerShell可操作的对象 $blobCheckResult = az storage blob exists --account-name test --container-name test --name $name --sas-token $sasToken | ConvertFrom-Json # 根据exists属性执行对应逻辑 if ($blobCheckResult.exists) { Write-Host "Blob已存在" } else { Write-Host "Blob不存在,执行上传操作" # 此处写入你的上传逻辑,例如: # az storage blob upload --account-name test --container-name test --file "本地文件路径" --name $name --sas-token $sasToken }
2. 带重试机制的do-while循环写法
如果需要自动重试直到Blob上传成功(存在),可以用do-while循环配合重试间隔:
$maxRetryTimes = 5 $retryGapSeconds = 10 $currentRetry = 0 $isBlobExists = $false do { # 检查Blob状态 $blobCheckResult = az storage blob exists --account-name test --container-name test --name $name --sas-token $sasToken | ConvertFrom-Json $isBlobExists = $blobCheckResult.exists if (-not $isBlobExists) { Write-Host "第$($currentRetry+1)次重试上传..." # 执行上传命令 az storage blob upload --account-name test --container-name test --file "本地文件路径" --name $name --sas-token $sasToken $currentRetry++ Start-Sleep -Seconds $retryGapSeconds } } while (-not $isBlobExists -and $currentRetry -lt $maxRetryTimes) if ($isBlobExists) { Write-Host "Blob上传成功并已存在" } else { Write-Host "达到最大重试次数,上传失败" }
关键说明
ConvertFrom-Json:将Azure CLI输出的JSON字符串转换为PowerShell对象,方便直接访问exists属性。- PowerShell中判断布尔值时,直接调用
$对象.属性即可,无需额外写-eq $true这类比较。 - 可根据实际需求调整
$maxRetryTimes(最大重试次数)和$retryGapSeconds(重试间隔)参数。
内容的提问来源于stack exchange,提问作者alcor8
相关产品推荐
相关产品推荐

