Search code examples
azurepowershellazure-storage

Azure blob version retention details using PowerShell


I am trying to find all blob versions in a container with its retention period. Basically we want to get this data to see what can be deleted from blob versions. I can see retention period of versions in Azure portal but not in PowerShell. I am trying below script. Can someone please guide me how can I get the same details using PowerShell?

Connect-AzAccount

Set-AzContext -Subscription "xxxxxxxxxxxxxxx"

$resourceGroup = "rg-dev-001"
$storageAccountName = "stdev"
$containerName = "offload"

$stoaccount = Get-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroup

$versions = Get-AzStorageBlob -Container $containerName -Context $stoaccount.Context -IncludeVersion -IncludeDeleted | where { $_.IsLatestVersion -NE 'True' }

Solution

  • I can see the retention period of versions in the Azure portal but not in PowerShell.

    In my environment, I have a file with a retention period and another file that doesn't have a retention period.

    Portal:

    enter image description here

    You can use the below PowerShell script to retrieve information.

    Command:

    Connect-AzAccount
    
    Set-AzContext -Subscription "xxxxxxxxxxxxxxx"
    
    $resourceGroup = "rg-dev-001"
    $storageAccountName = "stdev"
    $containerName = "offload"
    
    $stoaccount = Get-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroup
    
    $versions = Get-AzStorageBlob -Container $containerName -Context $stoaccount.Context -IncludeVersion -IncludeDeleted 
    
    Foreach($version in $versions){
       $properties = $version.BlobClient.GetProperties()
       Write-Host "URL: $($version.Context.BlobEndPoint)$($version.Container.Name)/$($version.Name)"
       Write-Host "TYPE: $($properties.Value.BlobType)"
       Write-Host "SIZE: $($properties.Value.ContentLength / 1KB) KiB"
       Write-Host "VERSION ID: $($properties.Value.VersionId)"
       Write-Host "RETENTION PERIOD: $($properties.Value.ImmutabilityPolicy.ExpiresOn)"
       write-Host " "
       }
    

    Output:

    URL: https://venkat789.blob.core.windows.net//example.pdf
    TYPE: Block
    SIZE: 22.166015625 KiB
    VERSION ID: 2023-09-11T15:05:29.3224280Z
    RETENTION PERIOD: 12/20/2023 15:06:41 +00:00
     
    URL: https://venkat789.blob.core.windows.net//table403 (1).txt
    TYPE: Block
    SIZE: 0.376953125 KiB
    VERSION ID: 2023-09-11T15:19:15.9233123Z
    RETENTION PERIOD: 
    

    enter image description here

    Reference:

    Manage block blobs with PowerShell - Azure Storage | Microsoft Learn