I am new to PowerShell and trying to get the tags for all the resources in multiple Azure subscriptions and send the output in the csv file. Below is the script, it is writing output on the screen but not in the csv file. Could anyone correct me, to export all data to csv file. Appreciate your help.
SubscriptionIds = Get-Content -Path "path for SubscriptionID.txt"
Foreach($SubscriptionId in $SubscriptionIds)
{
Try{$null = Set-AzContext -SubscriptionId $SubscriptionId}
catch [Exception] {write-host ("Error occured: " + $($_.Exception.Message)) -ForegroundColor Red;Exit}
Write-Host "Azure Login Session successful" -ForegroundColor Green -BackgroundColor Black
# Initialise output array
$Output = @()
# Collect all the groups from the current subscription
$ResourceGroups = Get-AzResourceGroup
foreach ($ResourceGroup in $ResourceGroups) {
Write-Host "Resource Group =$($ResourceGroup.ResourceGroupName)"
$resourceNames= Get-AzResource -ResourceGroupName $ResourceGroup.ResourceGroupName
$tags=Get-AzTag -ResourceId $ResourceGroup.ResourceId
foreach($key in $tags.Properties.TagsProperty.Keys)
{
Write-Host "`t ResourceGroup = $($ResourceGroup.ResourceGroupName) `t TagKey= $($key) `t Value = $($tags.Properties.TagsProperty.Item($($key)))"
}
foreach($res in $resourceNames)
{
Write-Host "ResourceName = $($res.Name)"
$tags=Get-AzTag -ResourceId $res.ResourceId
foreach($key in $tags.Properties.TagsProperty.Keys)
{
Write-Host "`t `t ResourceGroup = $($ResourceGroup.ResourceGroupName) `t ResourceName = $($res.Name) `t TagKey= $($key) `t Value = $($tags.Properties.TagsProperty.Item($($key)))"
}
}
}
# Sent the final output to CSV
$Output | Export-Csv -Path test.csv -NoClobber -NoTypeInformation -Append -Encoding UTF8 -Force
}