Powershell Add Tags To Resources
We'll be using Powershell 7 Preview that has AZ module to TAG resources
also, good to read the following article over MSDN Installing PowerShell Core on Windows
Azure PowerShell Az module
Powershell 7 Preview |
Az offers shorter commands, improved stability, and cross-platform support. Az also has feature equality with AzureRM, which provides a smooth migration path. Windows and PowerShell Core 6.x and later on all supported platforms - including Windows, macOS, and Linux.
Azure Tag All Resources in a Resource Group
Use the following script to read existing tags for the resource group and apply it to all its resources.- It will keep existing tags on resources that aren't duplicates
- If Resource Tag Key has empty value then it will replace it with resource group's same Tag key value if exists
# get resource group object
$group = Get-AzResourceGroup -Name TargetedResourceGroupName
#check if group have tags
if ($null -ne $group.Tags) {
#get all resources from
group
$resources = Get-AzResource -ResourceGroupName $group.ResourceGroupName
foreach ($r in $resources)
{
$resourcetags = (Get-AzResource -ResourceId $r.ResourceId).Tags
# print resource name
write-host $r.Name
# print new line
write-host
if ($resourcetags)
{
foreach ($key in $group.Tags.Keys)
{
if (-not($resourcetags.ContainsKey($key)))
{
$resourcetags.Add($key, $group.Tags[$key])
}
if(!$resourcetags[$key])
{
$resourcetags[$key]=$group.Tags[$key]
}
}
# write-host
$resourcetags
Set-AzResource -Tag $resourcetags -ResourceId $r.ResourceId
-Force
}
else
{
Set-AzResource -Tag $group.Tags
-ResourceId $r.ResourceId
-Force
}
}
}
Comments
Post a Comment