This script first connects to Azure and sets the tenant ID. It then gets all subscriptions in the tenant and creates a new CSV file to store all resource and resource group information. It writes the header row for the CSV file and then loops through each subscription.
For each subscription, the script selects it as the default and gets all resource groups in the subscription. It then loops through each resource group and gets all resources in the group. For each resource, the script gets the tags and converts them to a string. It then writes the resource information, including the subscription name, resource group name, resource name, and tags, to the CSV file.
After looping through all subscriptions, resource groups, and resources, the script closes the CSV file and disconnects from Azure.
# Connect to Azure account and verify your context
# Set the tenant ID
$tenantId = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
# Get all subscriptions in the tenant
$subscriptions = Get-AzSubscription -TenantId $tenantId
# Create a new CSV file to store all resource and resource group information
$csv = New-Object System.IO.StreamWriter "c:\temp\Resources.csv"
# Write the header row for the CSV file
$csv.WriteLine("Subscription,Resource Group,Resource,Tags")
# Loop through each subscription
foreach($subscription in $subscriptions)
{
# Select the subscription as the default
Select-AzSubscription -SubscriptionName $subscription.Name
# Get all resource groups in the subscription
$resourceGroups = Get-AzResourceGroup
# Loop through each resource group
foreach($resourceGroup in $resourceGroups)
{
# Get all resources in the resource group
$resources = Get-AzResource -ResourceGroupName $resourceGroup.ResourceGroupName
# Loop through each resource
foreach($resource in $resources)
{
# Get the tags for the resource
$tags = $resource.Tags
# Convert the tags to a string
$tagsAsString = ""
if ($null -ne $tags) {
#$tags.GetEnumerator() | ForEach-Object { $tagsAsString += $_.Key + ":" + $_.Value + ";" + "`n"}
$tags.GetEnumerator() | ForEach-Object { $tagsAsString += $_.Key + ":" + $_.Value + ";" + " "}
} else {
$tagsAsString = "NUll"
}
# Write the resource information to the CSV file
$csv.WriteLine("$($subscription.Name),$($resourceGroup.ResourceGroupName),$($resource.Name),$tagsAsString")
}
}
}
# Close the CSV file
$csv.Close()
# Disconnect from Azure
Please modify the script as per your custom requirement.
Source code can be found in URL:
If you need any assistance, please contact me using the contact form and I will try my best to assist you.