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).
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.
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.
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"
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With