Search code examples
azurepowershellazure-cli

Azure CLI IF on AZ Storage Blob Exists Results


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


Solution

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