azurepowershellazure-storage

PowerShell script to fetch Azure storage account based on tag name & value


I have a requirement to fetch storage account details with size in all subscriptions based on tag value & Name using PowerShell.

I'm using the below Get-Azstorageaccount module to fetch the details which is giving me the output with tags but I want to modify the script to filter out with specific tag name & value also with storage account size.

# Authenticate to Azure
Connect-AzAccount -Tenant 'xxxxx'-UseDeviceAuthentication
 
# Get all subscriptions in the current tenant
$subscriptions = Get-AzSubscription

# Define the Azure tag name
$tagName = "business"
$tagValue = "xyz"

# Filter storage accounts based on the tag
#$filteredStorageAccounts = $storageAccounts | Where-Object { $_.Tags[$tagName] } 

# Initialize an array to store storage account details
$storageAccounts = @()
 
foreach ($subscription in $subscriptions) {
    Write-Output "Processing subscription $($subscription.Name)..."

    # Set the current subscription context
    Select-AzSubscription -SubscriptionId $subscription.Id | Out-Null
    try {
        
        
        # Get all storage accounts in the subscription (Where-Object { $_.Tags[$tagName] -eq $tagValue })
        
        $storageAccounts += Get-AzStorageAccount | ForEach-Object {
            [PSCustomObject]@{
                SubscriptionName   = $subscription.Name
                ResourceGroupName  = $_.ResourceGroupName
                StorageAccountName = $_.StorageAccountName
                Location           = $_.PrimaryLocation
                AccountType        = $_.AccountType
                CreationTime       = $_.CreationTime
                TagName            = $_.Tags
            }
        }
    }
    catch {
        Write-Error "Error fetching storage accounts in subscription $($subscription.Name): $_"
    }
}
 
# Output the results
if ($storageAccounts) {
    $storageAccounts | Format-Table -AutoSize
}
else {
    Write-Output "No storage accounts found in any subscription."
}

Solution

  • PowerShell script to fetch Azure storage account based on tag name & value

    You can use the below script to fetch Azure storage account based on tag name & used capacity size also.

    Script:

    Connect-AzAccount -Tenant 'xxxxx'-UseDeviceAuthentication
    # Get all subscriptions
    $subscriptions = Get-AzSubscription
    
    # Define the tag key and value to filter by
    $tagKey = "xxx"
    $tagValue = "xxxx"
    
    # 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[$tagKey] -eq $tagValue }
    
        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=2018-01-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
            }
    
            # Add the storage account details and size to the results
            $results += [PSCustomObject]@{
                SubscriptionId   = $subscription.Id
                SubscriptionName = $subscription.Name
                ResourceGroup    = $storageAccount.ResourceGroupName
                StorageAccount   = $storageAccount.StorageAccountName
                UsedCapacityInBytes = $averageCapacity
            }
        }
    }
    
    # Output the results
    $results | Format-Table -AutoSize
    

    Output:

    SubscriptionId                       SubscriptionName                      ResourceGroup StorageAccount UsedCapacityInBytes
    --------------                       ----------------                      ------------- -------------- -------------------
    158b834xxxxxxxxxxxxxxx5-f21815dd048f xxxxxx xxxxxx xxxxxxxxxxx xxxxxxxxxxx venkatesan-rg venkat6781                75622151
    158b834xxxxxxxxxxxxxxx5-f21815dd048f xxxxxx xxxxxx xxxxxxxxxxx xxxxxxxxxxx venkatesan-rg venkat891                   543896
    

    enter image description here

    Reference:

    Metrics - List - REST API (Azure Monitor) | Microsoft Learn

    Updated Script:

    Connect-AzAccount -Tenant 'xxxxx' -UseDeviceAuthentication
    # Get all subscriptions
    $subscriptions = Get-AzSubscription
    
    # Define the tag key to filter by
    $tagKey = "createdby"
    
    # 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=2018-01-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
            }
    
            # Add the storage account details, size, and tags to the results
            $results += [PSCustomObject]@{
                SubscriptionId       = $subscription.Id
                SubscriptionName     = $subscription.Name
                ResourceGroup        = $storageAccount.ResourceGroupName
                StorageAccount       = $storageAccount.StorageAccountName
                UsedCapacityInBytes  = $averageCapacity
                TagName              = $tagKey
                TagValue             = $storageAccount.Tags[$tagKey]
            }
        }
    }
    
    # Output the results
    $results | Format-Table -AutoSize
    

    Output:

    SubscriptionId                       SubscriptionName                      ResourceGroup StorageAccount UsedCapacityInBytes TagName   TagValue
    --------------                       ----------------                      ------------- -------------- ------------------- -------   --------
    15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781                 6123454 createdby venkat  
    15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891                   693954 createdby venkat