What you could do is get the most recent modified container from the LastModified
property, then check if this timestamp is less than the current date minus 90 days. We would need to check both the container level and blob level LastModified properties.
# Set current context to subscription
Set-AzContext -SubscriptionId "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
# Go through every storage account in your subscription
foreach ($storageAccount in Get-AzStorageAccount) {
$storageAccountName = $storageAccount.StorageAccountName
$resourceGroupName = $storageAccount.ResourceGroupName
# Get key1 storage account key
$storageAccountKey = (Get-AzStorageAccountKey -Name $storageAccountName -ResourceGroupName $resourceGroupName).Value[0]
# Create storage account context using above key
$context = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey $storageAccountKey
# fetch all containers
$containers = Get-AzStorageContainer -Context $context
$deleteStorageAccount = $false
foreach ($container in $containers) {
# First check if container has been modified
if ($container.LastModified.DateTime -lt (Get-Date).AddDays(-90)) {
$deleteStorageAccount = $true
break
}
# Get all blobs from container, including deleted blobs
$blobs = Get-AzStorageBlob -Container $container.Name -Context $context -IncludeDeleted
# Then check each blob in container
foreach ($blob in $blobs) {
if ($blob.LastModified.DateTime -lt (Get-Date).AddDays(-90)) {
$deleteStorageAccount = $true
break
}
}
}
# If this flag is set, storage account has been acccessed in last 90 days
if ($deleteStorageAccount) {
Remove-AzStorageAccount -Name $storageAccountName -ResourceGroupName $resourceGroupName -Force -WhatIf
}
}
Since this action could be extremely harmful, you can run Remove-AzStorageAccount
with -WhatIf
to see what storage accounts will be deleted before deleting them for real.