Home > Blockchain >  Azure CLI IF on AZ Storage Blob Exists Results
Azure CLI IF on AZ Storage Blob Exists Results

Time:09-08

I have a usually reliable (but troublesome on one server) Azure Blob Storage automated backup process. I'd like my powershell script to retry the upload if for some reason it fails. I'm crafting an if statement (or a do while loop) when the file does not already exist in ABS. How do I capture the result of the Azure CLI call for AZ

My test attempt looks like this:

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"
}

The output of running the Azure CLI by itself is:

{
  "exists": true
}

I'm using too many languages these days, the syntax is always slightly different

CodePudding user response:

Capture the result of the Azure CLI call in a variable, something like $answer = az storage blob exists ...

Then test the answer's 'exists' property after you have converted it from JSON

if (($answer | ConvertFrom-Json).exists) {
    Write-Host "blob '$name' exists"
}
else {
    Write-Host "No blob called '$name' was found"
}

CodePudding user response:

Seems like you could approach it using this logic with a while loop:

$retries = 10
# substract 1 each iteration, while `$retries` is not equal to 0, this runs
while($retries) {
    # just output to the console in case you need to see what's going on
    Write-Host "Try # $retries..."
    # query azure
    $json = az storage blob exists --account-name test --container-name test --name $name --sas-token $sasToken
    # convert the output from Json and see if the `Exists` property is `$true`
    if($exists = ($json | ConvertFrom-Json).Exists) {
        # if it is, we can break this loop
        Write-Host 'Good to go!' -ForegroundColor Green
        break
    }
    # if it isn't, substract 1 from the counter
    $retries--
    # wait sometime, and go next iteration
    Start-Sleep -Milliseconds 200
}

# check one last time if the result was `$true`
if(-not $exists) {
    # if it isn't, halt the script
    throw 'thing does not exists, halting...'
}

# here we're good to go
  • Related