Running PowerShell script in all Azure subscriptions

I have a reference script below from (stackoverflow) which will fetch the storage account container details. it will output the subscription, storageaccount, container name and RG name.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Connect-AzAccount -Tenant 'xxxx' -UseDeviceAuthentication
#Set-AzContext -Subscription xxxx
$context = Get-AzContext
import-module az.resources
Get-AzSubscription | ForEach-Object {
# Set the context Details using Set-AzContext Command which is equalent to the az account set CLI Command
$_ | Set-AzContext
$subscriptionName = $_.Name
#<RUN YOUR SCRIPTS HERE>#
$storageAccounts = Get-AzResource -ResourceType 'Microsoft.Storage/storageAccounts'
[System.Collections.ArrayList]$saUsage = New-Object -TypeName System.Collections.ArrayList
foreach ($storageAccount in $storageAccounts) {
#list containers
$conatiners= Get-AzRmStorageContainer -ResourceGroupName $storageAccount.ResourceGroupName -StorageAccountName $storageAccount.Name
if($conatiners -ne $null){
foreach($container in $conatiners){
$StorageAccountDetails = [ordered]@{
SubscriptionName = $context.Subscription.Name
SubscrpitionID = $context.Subscription.Id
StorageAccountName = $storageAccount.Name
ContainerName = $container.Name
ResourceGroup = $storageAccount.ResourceGroupName
Location = $storageAccount.Location
}
$saUsage.add((New-Object psobject -Property $StorageAccountDetails)) | Out-Null
}
}else{
$StorageAccountDetails = [ordered]@{
SubscriptionName = $context.Subscription.Name
SubscrpitionID = $context.Subscription.Id
StorageAccountName = $storageAccount.Name
ContainerName = $null
ResourceGroup = $storageAccount.ResourceGroupName
Location = $storageAccount.Location
}
$saUsage.add((New-Object psobject -Property $StorageAccountDetails)) | Out-Null
}
}
}
$saUsage | Format-Table -AutoSize
</code>
<code>Connect-AzAccount -Tenant 'xxxx' -UseDeviceAuthentication #Set-AzContext -Subscription xxxx $context = Get-AzContext import-module az.resources Get-AzSubscription | ForEach-Object { # Set the context Details using Set-AzContext Command which is equalent to the az account set CLI Command $_ | Set-AzContext $subscriptionName = $_.Name #<RUN YOUR SCRIPTS HERE># $storageAccounts = Get-AzResource -ResourceType 'Microsoft.Storage/storageAccounts' [System.Collections.ArrayList]$saUsage = New-Object -TypeName System.Collections.ArrayList foreach ($storageAccount in $storageAccounts) { #list containers $conatiners= Get-AzRmStorageContainer -ResourceGroupName $storageAccount.ResourceGroupName -StorageAccountName $storageAccount.Name if($conatiners -ne $null){ foreach($container in $conatiners){ $StorageAccountDetails = [ordered]@{ SubscriptionName = $context.Subscription.Name SubscrpitionID = $context.Subscription.Id StorageAccountName = $storageAccount.Name ContainerName = $container.Name ResourceGroup = $storageAccount.ResourceGroupName Location = $storageAccount.Location } $saUsage.add((New-Object psobject -Property $StorageAccountDetails)) | Out-Null } }else{ $StorageAccountDetails = [ordered]@{ SubscriptionName = $context.Subscription.Name SubscrpitionID = $context.Subscription.Id StorageAccountName = $storageAccount.Name ContainerName = $null ResourceGroup = $storageAccount.ResourceGroupName Location = $storageAccount.Location } $saUsage.add((New-Object psobject -Property $StorageAccountDetails)) | Out-Null } } } $saUsage | Format-Table -AutoSize </code>
Connect-AzAccount -Tenant 'xxxx' -UseDeviceAuthentication

#Set-AzContext -Subscription xxxx


$context = Get-AzContext
import-module az.resources

Get-AzSubscription | ForEach-Object {
    # Set the context Details using Set-AzContext Command which is equalent to the az account set CLI Command
    $_ | Set-AzContext
    $subscriptionName = $_.Name
      #<RUN YOUR SCRIPTS HERE>#

$storageAccounts = Get-AzResource -ResourceType 'Microsoft.Storage/storageAccounts' 
[System.Collections.ArrayList]$saUsage = New-Object -TypeName System.Collections.ArrayList

 foreach ($storageAccount in $storageAccounts) {

   #list containers
   $conatiners= Get-AzRmStorageContainer -ResourceGroupName $storageAccount.ResourceGroupName -StorageAccountName $storageAccount.Name 

     if($conatiners -ne $null){
          foreach($container in $conatiners){
            $StorageAccountDetails = [ordered]@{
                    SubscriptionName = $context.Subscription.Name
                    SubscrpitionID = $context.Subscription.Id
                    StorageAccountName = $storageAccount.Name
                    ContainerName = $container.Name
                    ResourceGroup = $storageAccount.ResourceGroupName
                    Location = $storageAccount.Location
               }
             $saUsage.add((New-Object psobject -Property $StorageAccountDetails))  | Out-Null   
            }     
      }else{
      
        $StorageAccountDetails = [ordered]@{
                SubscriptionName = $context.Subscription.Name
                SubscrpitionID = $context.Subscription.Id
                StorageAccountName = $storageAccount.Name
                ContainerName = $null
                ResourceGroup = $storageAccount.ResourceGroupName
                Location = $storageAccount.Location      
         }
        $saUsage.add((New-Object psobject -Property $StorageAccountDetails)) | Out-Null
     }     
  }
}

$saUsage | Format-Table -AutoSize

I want the script to list the storage account container details and storage account size from all the subscriptions in my tenant filtered out by tagkey.

2

I want the script to list the storage account container details and storage account size from all the subscriptions in my tenant filtered out by tagkey.

You can use the below script to get the list of storage accounts with usage, container name and filtered out by tag key.

Script:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
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=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
foreach ($container in $containers) {
$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]
}
}
}
}
# Output the results
$results | Format-Table -AutoSize
</code>
<code> 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=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 foreach ($container in $containers) { $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] } } } } # Output the results $results | Format-Table -AutoSize </code>

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=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

        foreach ($container in $containers) {
        $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]
        }
      }
    }
}

# Output the results
$results | Format-Table -AutoSize

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>SubscriptionId SubscriptionName ResourceGroup StorageAccount ContainerName UsedCapacityInBytes TagName TagValue
-------------- ---------------- ------------- -------------- ------------- ------------------- ------- --------
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781 data 81178955 createdby venkat
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781 test 81178955 createdby venkat
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891 results 7577683 createdby venkat
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891 sample 7577683 createdby venkat
</code>
<code>SubscriptionId SubscriptionName ResourceGroup StorageAccount ContainerName UsedCapacityInBytes TagName TagValue -------------- ---------------- ------------- -------------- ------------- ------------------- ------- -------- 15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781 data 81178955 createdby venkat 15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781 test 81178955 createdby venkat 15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891 results 7577683 createdby venkat 15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891 sample 7577683 createdby venkat </code>
SubscriptionId                       SubscriptionName                      ResourceGroup StorageAccount ContainerName UsedCapacityInBytes TagName   TagValue
--------------                       ----------------                      ------------- -------------- ------------- ------------------- -------   --------
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781     data                     81178955 createdby venkat  
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat6781     test                     81178955 createdby venkat  
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891      results                   7577683 createdby venkat  
15xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxf xxxxxx xxxxxx xxxxxxxxxx Subscription venkatesan-rg venkat891      sample                    7577683 createdby venkat  

Reference:
PowerShell script to fetch Azure storage account based on tag name & value – Stack Overflow by me.

Recognized by Microsoft Azure Collective

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật