Search code examples
azureazure-blob-storageazure-storageazure-cli

How to check if Azure blob exists anywhere in storage account in multiple containers?


I have an Azure Storage account and in it are multiple Containers. How can I check all of the Containers to see if a specific named blob is in any of them? Also the blobs have multiple directories.
I know there's the az storage blob exists command, but that requires a Container name parameter. Will I have to use the List Containers command first?


Solution

  • Yes, you need to get the containers list. I have reproduced in my environment and got expected results as below and I followed Microsoft-Document:

    One of the way is Firstly, i have executed below code for getting containers list:

    $storage_account_name="rithemo"
    $key="T0M65s8BOi/v/ytQUN+AStFvA7KA=="
    $containers=az storage container list --account-name $storage_account_name  --account-key $key 
    $x=$containers | ConvertFrom-json
    $x.name
    

    enter image description here $key = Key of Storage Account

    Now getting every blob present in all containers in my Storage account:

    $Target = @()
    foreach($emo in $x.name )
     {
    $y=az storage blob list -c $emo --account-name $storage_account_name  --account-key $key
    $y=$y | ConvertFrom-json
    $Target += $y.name
    }  
    $Target
    

    enter image description here

    Now checking if given blob exists or not as below:

    $s="Check blob name"
     if($Target -contains $s){
    Write-Host("Blob Exists")
    }else{
     Write-Host("Blob Not Exists")
     }
     
    

    enter image description here

    Or you can directly use az storage blob exists command as below after getting containers list:

    foreach($emo in $x.name )
     {
    az storage blob exists --account-key $key --account-name $storage_account_name --container-name mycontainer --name $emo --name "xx"
    } 
    

    enter image description here