How to delete the specific tag of Azure VM using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

To delete the specific tag of the Azure VM, we can use the Delete property of the Operation parameter in the Update-AZTag command. In the below example, we have the below tags of the Azure VM TestMachine2k12.

Key             Value
---             -----
Patching_Day    Sunday
Owner           Chirag

We need to delete the Patching_Day tag and for that, we also need its value. The below command will delete the specified tag from the Azure VM.

PS C:\> $vm = Get-AzVM -VMName TestMachine2k12
PS C:\> $tag = @{'Patching_Day'='Sunday'}
PS C:\> Update-AzTag -ResourceId $vm.Id -Tag $tag -Operation Delete -Verbose

Once we check the tag, it should be deleted.

Get-AzVM -VMName TestMachine2k12 | Select -ExpandProperty Tags
Key   Value
---   -----
Owner Chirag

If you have the multiple tags to delete, provide key-value pair in the Tag hashtable. Like,

$tags = @{Patching_Day='Sunday'; Application='SecureTag'; Location='WestUS'}

And suppose we have multiple VMS with the same tag key (for example Patching_Day) but the different values then we need to retrieve each value of the tag for each VM.

$vms = @('AZVM1','AZVM2','AZVM3')
foreach($vm in $vms){
   $azvm = Get-AzVM -Name $vm
   $aztag = $azvm | Select -ExpandProperty Tags
   $Deletetag = @{'Patching_Day'= $aztag.Patching_Day}
   Update-AzTag -ResourceID $azvm.ID -tag $deletetag -Operation Delete -Verbose

The above code will delete the Patching_Day tag will its respective value on the VMs mentioned in the array.

Updated on 06-Apr-2021 07:51:36