Loading, please wait...

A to Z Full Forms and Acronyms

How to Update/Create Tag using PowerShell Script in Azure

Mar 24, 2022 Tags, 3150 Views
Azure - Tags Update/Create using PowerShell Script

How to Update/Create Tag using PowerShell Script in Azure

Azure - Tags Update/Create using PowerShell Script

The intent of this Article is to update/Create using Azure Powershell script. Sometimes we create Azure services however we forget to update Tags. Missing of Tags will cause lot of issues while trying to find the exact team for which service belongs to (In case of 1 single Subscription with many Azure Resource groups).

Also sometimes it will be painful process if you are dealing with 100’s of Azure Services in Environment and Updating them will be a cumbersome process. 

So how do we update them?

Lets take some use case scenario’s.

Currently in my sample example I have few NSG’s, So firstly i would like to find out if there are any tags associated with it or not. If not I want the list to be populated.

Next for all missing NSG’s i want to add a new tags.

Lets check it via Azure Powershell.

$resourcewithouttags = Get-AzResource -ResourceType “Microsoft.Network/networkSecurityGroups” | Where-Object {$null -eq $_.Tags -or $_.Tags.Count -eq 0} | Format-Table -AutoSize

 

 

So it gives me the 1 result back saying one of the NSG with the name: prademonsg001 does not have any tags. Lets validate the same through Azure Portal.

Let me expand prademonsg001

 

 

Which Confirms there are no tags associated.

Now lets try to add new Tags to this resource.

Now In order to add any new tags for any resource(s) we need to know the ResourceId. Lets try to get ResourceId for this NSG.

$gettingresourceIDs = Get-AzResource -ResourceType “Microsoft.Network/networkSecurityGroups”

I am specific using resourcetype as “Microsoft.Network/networkSecurityGroups” over here.

$tags = @{“Environment”=”Dev”; “Application”=”TestSoftware”}

Lets try to update NSG with new Tags.

As we may have multiple NSG’s in that case I am using “foreach” condition

 

Finally validate it from Azure Portal as well to make sure new Tags have been added to missing NSG’s.

In the case of creating new Tags please use “new-Aztag” Instead of “Update-aztag”

Entire Script:

$resourcewithouttags = Get-AzResource -ResourceType "Microsoft.Network/networkSecurityGroups" | Where-Object {$null -eq $_.Tags -or $_.Tags.Count -eq 0} | Format-Table -AutoSize 

$resourcewithouttags

$gettingresourceIDs = Get-AzResource -ResourceType "Microsoft.Network/networkSecurityGroups"
$Output = $gettingresourceIDs.Id
$Output


$tags = @{"Environment"="Dev"; "Application"="TestSoftware"}

foreach ($Output in $Output){
Write-Host "Processing "$condition"" -ForegroundColor Black -BackgroundColor white
Update-Aztag -ResourceId $Output -Tag $tags -Operation Merge 
}


A to Z Full Forms and Acronyms