This script is designed to identify resources that are missing tags in Azure subscriptions. It does this by first setting the tenant ID, which is a unique identifier for an Azure tenant. Then it gets all subscriptions in the tenant using the Get-AzSubscription
cmdlet and stores them in the $subscriptions
variable.
The script then iterates through each subscription in $subscriptions
and does the following:
- Creates an array called
$untaggedResources
to store the untagged resources for the subscription. - Gets all resource groups in the subscription using the
Get-AzResourceGroup
cmdlet and stores them in the$resourceGroups
variable. - For each resource group, the script gets all resources in the resource group using the
Get-AzResource
cmdlet and stores them in the$resources
variable. - For each resource, the script checks if the resource has no tags. If it does not have any tags, the script adds the resource to the
$untaggedResources
array. - After all resource groups have been processed, the script outputs the number of untagged resources in the subscription and exports the list of untagged resources to a CSV file in the
c:\temp
directory. The CSV file will be named$subscription-untaggedresources.csv
, where$subscription
is the name of the subscription.
# Set the tenant ID
$tenantId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# Get all subscriptions in the tenant
$subscriptions = Get-AzSubscription -TenantId $tenantId
foreach($subscription in $subscriptions)
{
$Path = "c:\temp"
# Create an array to store the untagged resources
$untaggedResources = @()
# Get all resource groups in the subscription
$resourceGroups = Get-AzResourceGroup
# Iterate through each resource group
foreach ($resourceGroup in $resourceGroups) {
# Get all resources in the resource group
$resources = Get-AzResource -ResourceGroupName $resourceGroup.ResourceGroupName
# Iterate through each resource
foreach ($resource in $resources) {
# Check if the resource has no tags
if ([string]::IsNullOrEmpty($resource.Tags)) {
# Add the resource to the untagged resources array
$untaggedResources += $resource
}
}
}
# Print the number of untagged resources
Write-Output "Number of untagged resources: $($untaggedResources.Count)"
$untaggedResources | Select-Object -Property Name, Resourcegroupname, Resourcetype, Tags | Export-Csv -path "$Path\$subscription-untaggedresources.csv" -NoTypeInformation
}
We can modify this further according to custom requirements.
Please find the code in resposirory:
https://github.com/riyasriy/Powershell/blob/main/export-untagged-resources.ps1
If you need any assistance with the script, please leave a comment below.