Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a blob already exists in Azure blob container using PowerShell

I have a Windows PowerShell script that uploads a file to my Azure Blob Storage. I want the file only to upload if it doesn't already exists in the container.

How do I check if the blob already exists ?

I tired to use Get-AzureStorageBlob but if the blob doesn't exists, it returns an error. Should I parse the error message to determine that the blob doesn't exists ? This doesn't seem right...

And Set-AzureStorageBlobContent is asking for a confirmation when the blob exists. Is there a way to automatically answer "No" ? This cmdlet doesn't have -confirm and -force would overwrite the file (which I don't want).

like image 613
Chris Avatar asked Feb 17 '15 20:02

Chris


People also ask

How do I check if a blob exists?

If you just need to know if the blob exists, you can make a simple HTTP HEAD request to the URI with any HTTP client. If you need the blob-reference for further use, there is a CloudBlobClient. GetBlobReferenceFromServer(Uri blobUri) method.

How do I check Azure blob?

View a blob container's contentsOpen Storage Explorer. In the left pane, expand the storage account containing the blob container you wish to view. Expand the storage account's Blob Containers. Right-click the blob container you wish to view, and - from the context menu - select Open Blob Container Editor.


2 Answers

This is a variant of @Chris's answer. Chris used Exceptions and Try/Catch. In larger systems try/catch is great. It allows an error deep in the code to throw an exception, and the system will backtrack the call history looking for a matching catch statement. However when all the code is in one function, for simplicity, I prefer checking return values:

$blob = Get-AzureStorageBlob -Blob $azureBlobName -Container $azureStorageContainer -Context $azureContext -ErrorAction Ignore
if (-not $blob)
{
    Write-Host "Blob Not Found"
}
like image 106
jimhark Avatar answered Oct 11 '22 00:10

jimhark


A solution is to wrap the call to Get-AzureStorageBlob in a try/catch and catch ResourceNotFoundException to determine that the blob doesn't exist.

And don't forget the -ErrorAction Stop at the end.

try
{   
    $blob = Get-AzureStorageBlob -Blob $azureBlobName -Container $azureStorageContainer -Context $azureContext -ErrorAction Stop
}
catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException]
{
    # Add logic here to remember that the blob doesn't exist...
    Write-Host "Blob Not Found"
}
catch
{
    # Report any other error
    Write-Error $Error[0].Exception;
}
like image 41
Chris Avatar answered Oct 11 '22 01:10

Chris