dcaz
dcaz

Reputation: 909

Update a value in a array of objects

If I have an array of objects like

$Results = @(
  [PSCustomObject]@{
    Email = $_.email
    Type  = $Type
  }
  # ...
)

and I want to update the 100th $results.type value from X to y. I thought this code would be

$results.type[100] = 'Hello'

But this is not working and I am not sure why?

Upvotes: 1

Views: 1476

Answers (2)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

$Results.Type[100] = 'Hello' doesn't work because $Results.Type isn't real!

$Results is an array. It contains a number of objects, each of which have a Type property. The array itself also has a number of properties, like its Length.

When PowerShell sees the . member invocation operator in the expression $Results.Type, it first attempts to resolve any properties of the array itself, but since the [array] type doesn't have a Type property, it instead tries to enumerate the items contained in the array, and invoke the Type member on each of them. This feature is known as member enumeration, and produces a new one-off array containing the values enumerated.

Change the expression to:

$Results[100].Type = 'Hello'

Here, instead, we reference the 101st item contained in the $Results array (which is real, it already exists), and overwrite the value of the Type property of that object.

Upvotes: 2

dcaz
dcaz

Reputation: 909

@MathiasR.Jessen answered this. The way I was indexing the array was wrong.

the correct way is $results[100].type = 'Hello'

Upvotes: 0

Related Questions