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

Chris picture Chris · Feb 17, 2015 · Viewed 11.5k times · Source

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).

Answer

jimhark picture jimhark · Apr 28, 2017

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