Skip to content

ForEach method behaving differently than ForEach-Object on Generic.List #25432

@DarkLite1

Description

@DarkLite1

Prerequisites

Steps to reproduce

Test data

$allFruits = [System.Collections.Generic.List[PSObject]]::new()
$fruits = [System.Collections.Generic.List[PSObject]]::new()

$allFruits.Add([PSCustomObject]@{Name = "banana"; Color = 'yellow' })
$fruits.Add([PSCustomObject]@{Name = "kiwi"; Color = 'green' })
$fruits.Add([PSCustomObject]@{Name = "cherry"; Color = 'red' })

Goal: Add $fruits to $allFruits

Test 1 : Fails

$fruits.ForEach({ $null = $allFruits.Add($_) })

$allFruits # banana yellow
$allFruits.Count # 3
$allFruits[1] # null

Test 1 : Success

$fruits | ForEach-Object { $allFruits.Add($_) }

$allFruits # banana yellow, kiwi green, cherry red
$allFruits.Count # 3
$allFruits[1] # kiwi   green

Expected behavior

We expected 3 items in the array the are accessible by using `$allFruits[N]`

Actual behavior

Using `$fruits.ForEach({ $null = $allFruits.Add($_) })` the count goes up correctly but items are not accessible on index.

Error details

Environment data

Name                           Value
----                           -----
PSVersion                      7.4.7
PSEdition                      Core
GitCommitId                    7.4.7
OS                             Microsoft Windows 10.0.20348
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-By DesignThe reported behavior is by design.WG-Enginecore PowerShell engine, interpreter, and runtimeWG-ReviewedA Working Group has reviewed this and made a recommendation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions