Azure Automation Runbook - Not Iterating Through All Subscriptions
Hello,
I am running an Azure Automation Runbook using a PowerShell script to iterate through all subscriptions and retrieve storage account details.
However, the script only retrieves data from the subscription where the Automation Account is located and does not switch to other subscriptions.
Issue:
Even after setting the context, the script does not access resources in other subscriptions. I do not get any errors, but the output only contains data from the Automation Account's subscription.
My Questions:
- How do I ensure the Automation Runbook can iterate through all subscriptions?
On my local PC in Powershell the script is working as expected
My PS script
# Import required Azure modules
Import-Module Az.Accounts
Import-Module Az.Storage
Import-Module Az.Resources
Import-Module SqlServer
# Authenticate to Azure using Managed Identity
....
Connect-AzAccount -Identity
.....
# Azure SQL Database connection details
...............
..............
# Retrieve all subscriptions
$subscriptions = Get-AzSubscription
foreach ($subscription in $subscriptions) {
Write-Output "Switching to Subscription: $($subscription.Name)"
# Set context to current subscription
Set-AzContext -SubscriptionId $subscription.Id
# Get all storage accounts in this subscription
$storageAccounts = Get-AzStorageAccount
foreach ($storageAccount in $storageAccounts) {
$accountName = $storageAccount.StorageAccountName
$resourceGroup = $storageAccount.ResourceGroupName
# Get Storage Account Key securely
$accountKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $accountName)[0].Value
# Create storage context
$ctx = New-AzStorageContext -StorageAccountName $accountName -StorageAccountKey $accountKey
# Get file shares containing "xxxxxxx"
$fileShares = Get-AzStorageShare -Context $ctx | Where-Object { $_.Name -match "xxxxxx" }
if ($fileShares.Count -eq 0) {
Write-Output "No file shares containing 'xxxxxx' found in $accountName."
continue
}
foreach ($share in $fileShares) {
try {
# Get share properties
$quotaGB = $share.Quota
$shareUsageInBytes = $share.ShareUsageInBytes
$shareUsageInGB = [math]::round($shareUsageInBytes / 1024 / 1024 / 1024, 2)
# Output details
Write-Output "Subscription: $($subscription.Name)"
Write-Output "Storage Account: $accountName"
Write-Output "File Share: $($share.Name)"
Write-Output "Quota (GB): $quotaGB"
Write-Output "Used Capacity (GB): $shareUsageInGB"
Write-Output "-----------------------------"
} catch {
Write-Output "Failed to retrieve stats for file share: $($share.Name). Error: $_"
}
}
}
}