Home > Net >  How delete VM Azure using tags using powershell?
How delete VM Azure using tags using powershell?

Time:08-26

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

CodePudding user response:

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:

CodePudding user response:

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
        }
    }
} 
  • Related