Restore a soft deleted blob with PowerShell

James Dumont le Douarec
Microsoft Azure
Published in
2 min readJun 14, 2021

Introduction

In this article we will see how to restore a blob that have been soft deleted.

To do that we will call the Azure API Undelete Blob with PowerShell.

Prerequisite

Attention : as illustrated in the following screenshot the “Owner” role doesn’t have DataActions permissions, this role is not enough to restore a blob that have been soft deleted.

Azure built-in role

Tips 1

Get your soft deleted blob based on a specific date.

#Get all deleted blob within a container$StorageAccount = Get-AzStorageAccount | Where-Object { $_.StorageAccountName -eq "<Your Storage Account Name>" }
$Blobs = Get-AzStorageContainer -Name "<Your Storage Account Container Name>" -Context $StorageAccount.Context | Get-AzStorageBlob -IncludeDeleted
#Get the soft deleted blobs on june 5, 2021$startDate = Get-Date -Year 2021 -Month 6 -Day 5
$endDate = Get-Date -Year 2021 -Month 6 -Day 6
$DeletedBlobs = $($Blobs | Where-Object { $_.IsDeleted -and $_.ICloudBlob.Properties.DeletedTime -ge $startDate -and $_.ICloudBlob.Properties.DeletedTime -le $endDate })

Tips 2

Get your Bearer access token

#Get your Bearer access token, run first Connect-AzAccount to authenticate on Azure$resource = “https://storage.azure.com"
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext
$accessToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, $resource).AccessToken

Tips 3

Call the Azure API Undelete Blob version 2017–11–09 that supports Bearer access tokens.

#request REST API$uri = “https://myaccount.blob.core.windows.net/mycontainer/myblob?comp=undelete"$headers = @{
‘Authorization’ = “Bearer $accessToken”;
‘x-ms-date’ = $((get-date -format r).ToString());
‘x-ms-version’ = “2017–11–09”;
}
Invoke-RestMethod -Method ‘Put’ -Uri $uri -Headers $headers

Conclusion

The full script →

Restore

When the PowerShell Az module doesn’t support something don’t hesitate to call Azure API!

Save

See You in the Cloud

Jamesdld

--

--