Norrin Rad
Norrin Rad

Reputation: 991

Get Vm's from RG with a particular tag value and update vm tags

I'm trying to do is check a tag from a RG which has been set to true, and then for those resources (vms) in the RG (which are currently set to $False) set those to true. I've got an update script

Trying to write an IF statement, which will pull outall tags which are set to true and then loop through the vms and set a tag on them to $true, bit stuck on the loop, if($OverRide -eq $true) { Get-AzureRmVM .. thats about as far as I got :)

$x = Get-AzureRmVm -name "ThisVM" -ResourceGroupName "ThisRG"
$tags = $x.Tags
$tags['Shutdown'] = "$True"
$UpdateTag = Set-AzureRmResource -Tag $tags $x

But its how do i get the vms from the RG with override set to true and then loop through each vm setting it to false.

Trying to write an IF statement, which will pull outall tags which are set to true and then loop through the vms and set a tag on them to $true, bit stuck on the loop,

if($OverRide -eq $true) {
        Get-AzureRmVm -ResourceGroupname | Where-Object { $_.Tags['ShutdownSchedule'] -eq $false } |`
         ForEach-Object { $tags = $_.Tags; $tags['ShutdownSchedule'] = $true; `
         $_ | Set-AzureRmResource -Tag $tags } 

Hope that makes more sense

Update..

something like that, gets all RG's similar to This-RG and gets the RG name and then passes that into a loop catching all vm's

$resourcegroup = get-AzureRmResourceGroup | where -FilterScript {
   $_.ResourceGroupName -like "This-RG*"
   }

$rgname = $resourcegroup | select resourcegroupname

Get-AzureRmVm | foreach ($rgname in $rgnames) 
{ 
Where-Object { $_.Tags['Shutdown'] -eq $false } | ForEach-Object`
{ $tags = $_.Tags; $tags['Shutdown'] = $true; $_ | Set-AzureRmResource -Tag $tags }
}

Upvotes: 0

Views: 7355

Answers (1)

4c74356b41
4c74356b41

Reputation: 72151

$resourceGroups = Get-AzureRmResourceGroups | Where-Object { $_.Tags['Shutdown'] -eq $false -and $_.Name -like 'This-RG*' }

$resourceGroups.ForEach({
    $vms = Get-AzureRmVm -resourceGroup $_.Name
    $vms.ForEach({
        $tags = $_.Tags
        $tags['Shutdown'] = $true;
        Set-AzureRmResource -ResourceId $_.Id -Tag $tags
    })
})

This will find all the resource groups with tag shutdown equals to false and change shutdown tag on all the vms inside those groups to true

Upvotes: 1

Related Questions