skip to Main Content

How do I delete a VM using tags? Let’s say there is a VM with the tags "Name:Surname". How can I delete this VM without using the VM name or ID. Namely deletion using tags.
I try to use:

get-azvm -ResourceGroupName "ResourceGroup" | Where-Object {$_.Tags -like "[Name, blabla], [Surname, blabla]"}

but it didn’t find that VM

2

Answers


  1. I have reproduced in my environment. Firstly, you need to find the Virtual Machine using the below command:

    xx- Name of the resource group

    hello- tag name

    get-azvm -ResourceGroupName "xx" | Where-Object {$_.Tags['hello']}
    

    enter image description here

    After getting the VM name you can use the below command to delete the VM:

    xx- Name of the resource group
    yy- Name of the vm.

    Remove-AzVM -ResourceGroupName "xx" -Name "yy"
    

    Then type Y(yes) to delete the VM as below:

    enter image description here

    References taken from:

    Login or Signup to reply.
  2. Based on this,
    You could do something like this:

    $Surname= 'Test'
    $VMs = Get-AzVM -ResourceGroupName 'myRG'
    foreach ($VM in $VMs)
    {
        [Hashtable]$VMTag = (Get-AzVM -ResourceGroupName $VM.ResourceGroupName -Name  $VM.Name).Tags
        foreach ($h in $VMTag.GetEnumerator()) {
        if (($h.Name -eq "Name") -and ($h.value -eq $Surname))
            {
                Write-host "Removing VM" $VM.Name
                Remove-AzVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -Confirm:$false
            }
        }
    } 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search