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?
CodePudding user response:
$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.
CodePudding user response:
@MathiasR.Jessen answered this. The way I was indexing the array was wrong.
the correct way is $results[100].type = 'Hello'