Share via


How to tag a virtual machine in Azure using PowerShell

Applies to: ✔️ Linux VMs ✔️ Windows VMs ✔️ Flexible scale sets ✔️ Uniform scale sets

This article describes how to tag a VM in Azure using PowerShell. Tags are user-defined key/value pairs which can be placed directly on a resource or a resource group. Azure currently supports up to 50 tags per resource and resource group. Tags may be placed on a resource at the time of creation or added to an existing resource. If you want to tag a virtual machine using the Azure CLI, see How to tag a virtual machine in Azure using the Azure CLI.

Use the Get-AzVM cmdlet to view the current list of tags for your VM.

Get-AzVM -ResourceGroupName "myResourceGroup" -Name "myVM" | Format-List -Property Tags

If your Virtual Machine already contains tags, you will then see all the tags in list format.

To add tags, use the Set-AzResource command. When updating tags through PowerShell, tags are updated as a whole. If you are adding one tag to a resource that already has tags, you will need to include all the tags that you want to be placed on the resource. Below is an example of how to add additional tags to a resource through PowerShell Cmdlets.

Assign all of the current tags for the VM to the $tags variable, using the Get-AzResource and Tags property.

$tags = (Get-AzResource -ResourceGroupName myResourceGroup -Name myVM).Tags

To see the current tags, type the variable.

$tags

Here is what the output might look like:

Key           Value
----          -----
Department    MyDepartment
Application   MyApp1
Created By    MyName
Environment   Production

In the following example, we add a tag called Location with the value myLocation. Use += to append the new key/value pair to the $tags list.

$tags += @{Location="myLocation"}

Use Set-AzResource to set all of the tags defined in the $tags variable on the VM.

Set-AzResource -ResourceGroupName myResourceGroup -Name myVM -ResourceType "Microsoft.Compute/VirtualMachines" -Tag $tags

Use Get-AzResource to display all of the tags on the resource.

(Get-AzResource -ResourceGroupName myResourceGroup -Name myVM).Tags

The output should look something like the following, which now includes the new tag:


Key           Value
----          -----
Department    MyDepartment
Application   MyApp1
Created By    MyName
Environment   Production
Location      MyLocation

Next steps