1

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?

3
  • 2
    $results[100].type = 'Hello' Commented Oct 4, 2021 at 19:46
  • yeah ? If that works I will be mad. Commented Oct 4, 2021 at 19:46
  • @MathiasR.Jessen change to answer, Thanks Commented Oct 4, 2021 at 20:09

2 Answers 2

2

$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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.