Index operation failed; the array index evaluated to null

Hi All,

I’m trying to overwrite existing azure resourc tags with the tags mentioned in csv file, I have below script but it gives an error “Index operation failed; the array index evaluated to null”

however when I remove “foreach ($tagName in $newTags.Keys){$tags[$] = $newTags[$]}” lines the script works but updates same tag for all resources (e.g. app tag, has diff values but the same value is updated for all resources, it should update vm1 with app1, vm2 with app2 etc… but vm1 and vm2 gets app1 only)

any help is much appreciated :slight_smile:

$csv = Import-Csv "C:\CT - Copy.csv"

$csv | ForEach-Object {
# Retrieve existing tags
$tags = (Get-AzureRmResource -ResourceGroupName $_.ResourceGroup -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.Name).Tags

$newTags += @{
app= $_.app
dsc= $_.dsc
stop= $_.stop
start= $_.start

}

foreach ($tagName in $newTags.Keys){
$tags[$_] = $newTags[$_]
}

Set-AzureRmResource -ResourceGroupName $_.ResourceGroup -Name $_.Name -Tag $newtags -ResourceType "Microsoft.Compute/virtualMachines" -verbose -Force
}

This…

foreach ($tagName in $newTags.Keys){
$tags[$_] = $newTags[$_]
}

… is not correct, in a normal case. You don’t have a variable called $tags anywhere in your ForEach scope. You have tagname.

So, this forloop …

$newTags += @{
    app= $_.app
    dsc= $_.dsc
    stop= $_.stop
    start= $_.start
}

$newTags|ft -a

Name  Value
----  -----
dsc        
app        
stop       
start      


# What happnes in the loop
foreach ($tagName in $newTags.Keys)
{
    ($tagName[$_] = $newTags[$_])
}

Index operation failed; the array index evaluated to null.
At line:3 char:6
+     ($tagName[$_] = $newTags[$_])
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArrayIndex
 ...



Change

foreach ($tagName in $newTags.Keys)
{
    ($tagName = $newTags)
}

Name                           Value
----                           -----
dsc
app
stop
start
dsc
app
stop
start
dsc
app
stop
start
dsc
app
stop
start

Are you sure this is what you are after, and you need to handle all the spaces this kind of thing creates.

Hi Postanote,

thanks it makes sense now and I don’t think this is what I wanted at least after looking at the corrected output.

What I’m trying is …

To write a script which will take input from csv, that csv has info of resources from multiple subscriptions and what there tags should be…but I couldn’t make it work , either it performs tag updates on resources only from single subscription at a time (csv doesn’t have info on subscription of the resources) or updates same tag on all resources …appreciate any guidance/help

thanks again :slight_smile: