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