How to add the tag of Azure VM using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To add the tag to the Azure VM we need to use the Update-AZTag command. This command will merge the new tag to the existing tag(s) of the VM. If you are planning to add the entirely new VM tag, you can use the New-AZTag command. Once you use the New-AZTag command, other tags will be deleted for that particular VM and the New tag will be created so pls be careful with that command.

We have the VM called TestMachine2k12 on Azure and there are few existing tags applied to the VM as shown below.

Example

Get-AzVM -Name TestMachine2k12 | Select -ExpandProperty Tags

Output

We need to add the new tag called Patching_Day and its value should be Sunday. We will first create a tag that is a Hashtable with its name and associated value as shown below.

$tag = @{'Patching_Day' = 'Monday'}

Once the tag is created, we can use the Update-AZTag command. This command uses the resource ID. So we need VM resource ID to apply the tag.

PS C:\> $vm = Get-AzVM -Name TestMachine2k12
PS C:\> Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Merge -Verbose

Here, we are retrieving the VM information first to get the resource ID of it and you might have noticed that we are using Merge operation here. When you check the applied tag, it should show.

If you have multiple tags for the single VM then, you can add the additional tag to the TAG hashtable by a semicolon as shown below.

$tag = @{'Patching_Day' = 'Sunday'; 'App_Owner'='James Clean'}

You can use the Update-AZTag command to update the tag. When you have more than one VM to apply the same tag then you can use the foreach loop for it and if you have different tags for the different VMs then we can use the CSV file which has VM and associated tags and then foreach loop to apply the tag.

raja
Published on 06-Apr-2021 11:19:05
Advertisements