Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

An attempt to modify a collection while it is being enumerated doesn't always result in an error #20181

Copy link
Copy link
@mklement0

Description

@mklement0
Issue body actions

Prerequisites

Steps to reproduce

Attempting modification of a collection while it is being enumerated should result in an error:

  • An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not execute.

This error isn't consistently surfaced - note that this is a regression from Windows PowerShell:

# OK: Reports an error for the attempt to modify the collection being enumerated.
'--- foreach'
$l = [System.Collections.Generic.List[string]] @('one', 'two')
foreach ($e in $l) { $l.Remove($e) }

# !! Fails QUIETLY in PS CORE as of v7.4.0-preview.5
'--- pipeline'
$l = [System.Collections.Generic.List[string]] @('one', 'two')
$l | ForEach-Object { $l.Remove($_) }

Important: The quiet failure only occurs when the code is executed via a script file; if you paste the last two statements into an interactive console, the error does surface.

[Update: NOT PowerShell's fault - see below] The following WinForms example affects Windows PowerShell too (both interactively and in a script):

using namespace System.Windows.Forms
Add-Type -Assembly System.Windows.Forms

$f = [Form]::new()
$f.Controls.AddRange((
  [CheckBox]::new(),
  [CheckBox]::new()
))

# !! Should fail with an error message, but quietly aborts after the first .Remove() call.
$f.Controls | ForEach-Object { $f.Controls.Remove($_) }

$f.Controls.Count # !! still nonzero

Expected behavior

First snippet:

  • Both the foreach and the ForEach-Object statement should report the expected error.

Second snippet:

  • The expected error should occur.

Actual behavior

First snippet:

  • The ForEach-Object statement doesn't report an error and quietly aborts the pipeline after the first .Remove() call

Second snippet:

  • The expected error doesn't occur; quietly aborts the pipeline after the first .Remove() call.

Error details

No response

Environment data

PowerShell 7.4.0-preview.5

Visuals

No response

Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    In-PRIndicates that a PR is out for the issueIndicates that a PR is out for the issue

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.