Home > front end >  How to check if Azure blob exists anywhere in storage account in multiple containers?
How to check if Azure blob exists anywhere in storage account in multiple containers?

Time:12-20

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?

CodePudding user response:

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

CodePudding user response:

Yes, you will need to use the List Containers command to get a list of all the containers in your storage account, and then you can loop through the list of containers and check each one for the specific blob that you are looking for.

Here's an example of how you can accomplish this using the Azure CLI

# First, get a list of all the containers in your storage account
containers=$(az storage container list --account-name YOUR_STORAGE_ACCOUNT_NAME --output tsv --query '[].name')

# Loop through the list of containers
for container in $containers
do
    # Check if the specific blob exists in the current container
    az storage blob exists --account-name YOUR_STORAGE_ACCOUNT_NAME --container-name $container --name YOUR_BLOB_NAME
    # If the blob exists, print a message and break out of the loop
    if [ $? -eq 0 ]; then
        echo "Blob found in container: $container"
        break
    fi
done
  • Related