The below PowerShell script provides directory details filtered with directory name “internal” and tag name ” Business” also with container name “landing”, I noticed few storage accounts with project directories inside directory “internal” and trying to list them all in the output.
I tested adding -prefix internal to $directories variable but this is not giving me desired result.
I need to list all directories inside a parent directory named internal under container landing.
Connect-AzAccount -Tenant 'xxxxx' -UseDeviceAuthentication
# Get all subscriptions
$subscriptions = Get-AzSubscription
# Define the tag key to filter by
$tagKey = "Business"
# Initialize an array to store the results
$results = @()
foreach ($subscription in $subscriptions) {
# Set the current subscription context
Set-AzContext -SubscriptionId $subscription.Id
# Get all storage accounts in the current subscription
$storageAccounts = Get-AzStorageAccount | Where-Object { $_.Tags.ContainsKey($tagKey) }
foreach ($storageAccount in $storageAccounts) {
# Get the metrics for the storage account
$resourceId = "/subscriptions/$($subscription.Id)/resourceGroups/$($storageAccount.ResourceGroupName)/providers/Microsoft.Storage/storageAccounts/$($storageAccount.StorageAccountName)"
$uri = "https://management.azure.com$resourceId/providers/Microsoft.Insights/metrics?api-version=2023-10-01&metricnames=UsedCapacity&aggregation=Average"
try {
$response = Invoke-AzRestMethod -Method Get -Uri $uri
$metrics = $response.Content | ConvertFrom-Json
$usedCapacityMetric = $metrics.value | Where-Object { $_.name.value -eq "UsedCapacity" }
if ($usedCapacityMetric) {
$averageCapacity = $usedCapacityMetric.timeseries.data.average | Measure-Object -Sum | Select-Object -ExpandProperty Sum
} else {
$averageCapacity = 0
}
} catch {
Write-Warning "Failed to retrieve metrics for storage account: $($storageAccount.StorageAccountName)"
$averageCapacity = 0
}
$ctx = $storageAccount.Context
$containers = Get-AzStorageContainer -Context $ctx | Where-Object { $_.Name -eq "landing" }
foreach ($container in $containers) {
$prefix = "internal"
$blobs = Get-AzStorageBlob -Prefix "internal" -Container $container.Name -Context $ctx
$directories = $blobs | ForEach-Object {
$parts = $_.Name.Split('/')
for ($i = 0; $i -lt $parts.Length - 1; $i++) {
$parts[0..$i] -join '/'
}
} | Sort-Object -Unique
$results += [PSCustomObject]@{
#SubscriptionId = $subscription.Id
SubscriptionName = $subscription.Name
ResourceGroup = $storageAccount.ResourceGroupName
StorageAccount = $storageAccount.StorageAccountName
ContainerName = $container.Name
UsedCapacityInBytes = $averageCapacity
TagName = $tagKey
TagValue = $storageAccount.Tags[$tagKey]
Directories = $directories -join ", "
}
}
}
# Output the results
$results | Format-Table -AutoSize
[![current PowerShell output][1]][1]