Reputation: 47
I have written a PowerShell script to retrieve list of Azure recovery service vaults across multiple subscription.
This is my code:
$subscriptions = Get-AzSubscription
ForEach ($Subscription in $Subscriptions) {
Set-AzContext -SubscriptionId 77a74465-c065-4108-b270-edd84f918fe0
$vaults = get-azrecoveryservicesvault
ForEach ($vault in $vaults)
{
Set-AzRecoveryServicesVaultContext -Vault $vault
Get-AzRecoveryServicesVault |Select-Object "Name","ResourceGroupName","Location","SubscritptionId" | Export-Csv "C:\RSV-Report.csv" -NoTypeInformation -Encoding ASCII -Append
}
}
This returns an output like this:
It is not returning the Subscription IDs for all the resources.
But, when I am calling single subscription and single resource group with this code:
Set-AzContext -SubscriptionId 77a74465-c065-4108-b270-********
Get-AzRecoveryServicesVault | Select-Object "Name","ResourceGroupName","Location","SubscriptionId" | Export-Csv "C:\report1.csv" -NoTypeInformation -Append
I get a perfect output:
I want the output to look the same as for a single subscription and single resource group for all at once.
I need help for output like above and I also want get subscription Name column. I tried to pass subscription name in select-object in above codes but it gives blank entry in rows for subscription name column.
I want to thank in advance if anyone could help me.
I am new to powershell, I keep trying to resolve this issue.
Upvotes: 0
Views: 1815
Reputation: 61253
You are using the same SubscriptionId in each iteration hardcoded, where you should use the Id
property from each $Subscription object you received with the Get-AzSubscription
call.
Try
$subscriptions = Get-AzSubscription
# loop through the subscriptions and collect the output in variable $result
$result = foreach ($Subscription in $Subscriptions) {
$null = Set-AzContext -SubscriptionId $Subscription.Id
$vaults = Get-AzRecoveryServicesVault
foreach ($vault in $vaults) {
Set-AzRecoveryServicesVaultContext -Vault $vault
# output a PSObject with the chosen properties
Get-AzRecoveryServicesVault | Select-Object "Name","ResourceGroupName","Location","SubscriptionId"
}
}
$result | Export-Csv "C:\RSV-Report.csv" -NoTypeInformation -Encoding ASCII
Upvotes: 1