Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created July 2, 2021 12:03
Show Gist options
  • Save JohnLBevan/e2502af9ca6a6bdb9a7780ca9f0810bc to your computer and use it in GitHub Desktop.
Save JohnLBevan/e2502af9ca6a6bdb9a7780ca9f0810bc to your computer and use it in GitHub Desktop.
Remove trailing spaces from Azure tag names
#
# Rough and ready script to clean up trailing spaces from tag names
# Loops through all resources and resource groups under all subscriptions to which you have access.
# If a resource isn't already tagged with the clean (same name with no trailing space) then the clean tag name is given the diry tag's value, and the dirty tag is removed.
# If a resource has both clean and dirty tags, this shows a warning (even if the values are the same... I was lazy / didn't add a check for that) and leaves to the caller to fix manually.
# If a resource doesn't have any dirty tags, it's not affected.
#
Clear-Host
Login-AzAccount # (interactive / opens web browser)
$subs = Get-AzSubscription
foreach ($sub in $subs) {
Write-Verbose "Processing sub $($sub.Name)" -Verbose
Set-AzContext -SubscriptionObject $sub | Out-Null
[PSObject[]]$tags = Get-AzTag -Detailed | ?{$_.Name -like '* '}
foreach ($tag in $tags) {
foreach ($value in $tag.Values.Name) {
$rs = Get-AzResource -Tag @{"$($tag.Name)" = "$value"}
$rgs = Get-AzResourceGroup -Tag @{"$($tag.Name)" = "$value"}
foreach ($r in $rs) {
Write-Verbose "- resource: $($r.ResourceId)" -Verbose
$rt = $r.Tags
if ($rt.Keys -contains "$($tag.Name.Trim())") {
Write-Warning "- - Trimmed tag already exists; not updated: $($tag.Name)"
} else {
$rt.Add("$($tag.Name.Trim())", $value)
$rt.Remove($tag.Name)
Set-AzResource -ResourceId $r.ResourceId -Tag $rt -Force
Write-Verbose "- - UPDATED: $($tag.Name)" -Verbose
}
}
foreach ($rg in $rgs) {
Write-Verbose "- resource group: $($rg.ResourceId)" -Verbose
$rgt = $rg.Tags
if ($rgt.Keys -contains "$($tag.Name.Trim())") {
Write-Warning "- - Trimmed tag already exists; not updated: $($tag.Name)"
} else {
$rgt.Add("$($tag.Name.Trim())", $value)
$rgt.Remove($tag.Name)
Set-AzResourceGroup -ResourceId $rg.ResourceId -Tag $rgt
Write-Verbose "- - UPDATED: $($tag.Name)" -Verbose
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment