lubierzca
lubierzca

Reputation: 160

Assign tag to all VMs at once

I want to add the same tag value for all VM's in every resouce group in Azure.

I already prepared a script, but PS doesn't want to proceed with this, because of object to string conversion thingy.

$VMs = Get-AzureRmVM

$VMs | Foreach-Object {
$t = Get-AzureRmResource -ResourceName $VMs.Name -ResourceGroupName $VMs.ResourceGroupName
Set-AzureRmResource -Tag @{ Funding="..."} -ResourceId $t.ResourceId -Force
}

But how can I do loops, when it asks for a string, when objects parsed to loop must clearly be object? Am I forced to prepare external list in a txt file and parse values from there as strings?

Upvotes: 1

Views: 656

Answers (1)

Theo
Theo

Reputation: 61208

Inside the ForEach-Object loop, you should use the automatic variable $_ to target that one particular object. Now you are sending arrays to the Get-AzureRmResource cmdlet:

$VMs = Get-AzureRmVM

$VMs | Foreach-Object {
    $t = Get-AzureRmResource -ResourceName $_.Name -ResourceGroupName $_.ResourceGroupName
    Set-AzureRmResource -Tag @{ Funding="..."} -ResourceId $t.ResourceId -Force
}

Suppose you have three VMs you get back from $VMs = Get-AzureRmVM
(I faked that here using an array of [PSCustomObject] objects)

$VMs = @(
    [PSCustomObject]@{Name = 'VM1'; ResourceGroupName = 'VM1_Resource'},
    [PSCustomObject]@{Name = 'VM2'; ResourceGroupName = 'VM2_Resource'}
    [PSCustomObject]@{Name = 'VM3'; ResourceGroupName = 'VM3_Resource'}
)

Then performing $VMs.Name results in (Object[]) array 'VM1','VM2','VM3'

and performing $VMs.ResourceGroupName results in an array 'VM1_Resource','VM2_Resource','VM3_Resource'

Inside the loop however, the variable $_ represents only one of these VM's in turn, so for the first iteration $_.Name is a string "VM1" etc.

Hope that explains your object to string conversion thingy.

Upvotes: 1

Related Questions