Forum Discussion
Fromelard
May 15, 2024Steel Contributor
Azure - PowerShell Script to delete a specific Tag for any resources in all your Subscriptions
A classical question after many months of usage and delegation to different admin is related to the TAG Cleanup.
You can be faced to a large diversity of Tags created at one moment, but not useful and mainly not maintained.
This small script will help you to execute this cleanup in all your subscriptions you are in charge.
Import-module Az
Connect-AzAccount
[string]$TagName = "YourSpecificTagKey"
$TagCount = 0
$All_Az_Subscriptions = Get-AzSubscription
Foreach ($Az_Subscription in $All_Az_Subscriptions)
{
Write-Host " "
Write-Host " --------------------------------------- "
Write-Host "Working on subscription ""$($Az_Subscription.Name)""" -foregroundcolor "yellow"
$TagCount = 0
Set-AzContext -SubscriptionObject $Az_Subscription | Out-Null
$AllTaggedresources = Get-AzResource -TagName $TagName
$TagCount = $AllTaggedresources.Count
Write-Host " >> TAG "" $($TagName) "" found "" $($TagCount) "" times" -foregroundcolor "green"
if($TagCount -gt 0)
{
$AllTaggedresources.ForEach{
if ( $_.tags.ContainsKey($TagName) ) {
$_.tags.Remove($TagName)
}
$_ | Set-AzResource -Tags $_.tags -Force
}
}
}
This script was inspired by these pages:
- https://stackoverflow.com/questions/54162372/how-to-fix-this-error-in-azure-powershell-can-not-remove-tag-tag-value-becaus
- https://learn.microsoft.com/en-us/powershell/module/az.resources/set-azresource?view=azps-11.6.0
Fabrice Romelard
No RepliesBe the first to reply