question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Collection was modified; enumeration operation may not execute when running Invoke-ScriptAnalyzer

See original GitHub issue

Before submitting a bug report:

  • Perform a quick search for existing issues to check if this bug has already been reported

This may be related to: PSUseToExportFieldsInManifest throw System.InvalidOperationException: Collection was modified; enumeration operation may not execute #902

Steps to reproduce

PSScriptAnalyzer - Collection was modified.zip

  1. Unzip the above into a folder.
  2. Open that folder in PowerShell 7.
  3. Execute: $x = .\Test.ps1 -Run 10 -SAVersion '1.19.0'
  4. The results will contain entries with Collection was modified; enumeration operation may not execute exceptions. If run several times different files will have these exceptions.

Expected behavior

No Collection was modified; enumeration operation may not execute. issues.

If I change to a previous version of the module the issue goes away:

  1. Unzip the above into a folder.
  2. Open that folder in PowerShell 7.
  3. Execute: $x = .\Test.ps1 -Run 10 -SAVersion '1.18.3'
  4. The results will contain NO Collection was modified; enumeration operation may not execute exceptions. If run several times there will never be any such exceptions.

Actual behavior

Several issues are returned. If run multiple times different files show the issues. Sample error message:

Invoke-ScriptAnalyzer: C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Test.ps1:29
Line |
  29 |  …     $issues = Invoke-ScriptAnalyzer -Path $file -Settings $settings `
     |                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Collection was modified; enumeration operation may not execute.

If an unexpected error was thrown then please report the full error details using e.g. $error[0] | Select-Object *

PSMessageDetails      :
Exception             : System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
                           at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
                           at System.Management.Automation.CommandInfo.get_Parameters()
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules.UseCorrectCasing.AnalyzeScript(Ast ast, String fileName)+MoveNext()
                           at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
                           at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
                           at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.<>c__DisplayClass82_1.<AnalyzeSyntaxTree>b__2()
TargetObject          : C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Functions\Private\Get-HFGitStatus.ps1
CategoryInfo          : InvalidOperation: (C:\Data\PowerShell\…Get-HFGitStatus.ps1:String) [Invoke-ScriptAnalyzer], InvalidOperationException
FullyQualifiedErrorId : RULE_ERROR,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeScriptAnalyzerCommand
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Test.ps1: line 29
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {0, 1}
> Get-Error -InputObject $x[0].ErrorRecord

Exception             :
    Type       : System.InvalidOperationException
    TargetSite :
        Name          : ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion
        DeclaringType : System.ThrowHelper, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
        MemberType    : Method
        Module        : System.Private.CoreLib.dll
    StackTrace :
   at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
   at System.Management.Automation.CommandInfo.get_Parameters()
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.BuiltinRules.UseCorrectCasing.AnalyzeScript(Ast ast, String fileName)+MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Microsoft.Windows.PowerShell.ScriptAnalyzer.ScriptAnalyzer.<>c__DisplayClass82_1.<AnalyzeSyntaxTree>b__2()
    Message    : Collection was modified; enumeration operation may not execute.
    Source     : System.Private.CoreLib
    HResult    : -2146233079
TargetObject          : C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Functions\Private\Get-HFGitStatus.ps1
CategoryInfo          : InvalidOperation: (C:\Data\PowerShell\…Get-HFGitStatus.ps1:String) [Invoke-ScriptAnalyzer], InvalidOperationException
FullyQualifiedErrorId : RULE_ERROR,Microsoft.Windows.PowerShell.ScriptAnalyzer.Commands.InvokeScriptAnalyzerCommand
InvocationInfo        :
    MyCommand        : Invoke-ScriptAnalyzer
    ScriptLineNumber : 29
    OffsetInLine     : 19
    HistoryId        : 12
    ScriptName       : C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Test.ps1
    Line             : $issues = Invoke-ScriptAnalyzer -Path $file -Settings $settings `

    PositionMessage  : At C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Test.ps1:29 char:19
                       + …     $issues = Invoke-ScriptAnalyzer -Path $file -Settings $settings `
                       +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PSScriptRoot     : C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified
    PSCommandPath    : C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Test.ps1
    InvocationName   : Invoke-ScriptAnalyzer
    CommandOrigin    : Internal
ScriptStackTrace      : at <ScriptBlock>, C:\Data\PowerShell\Miscellaneous\Issues\PSScriptAnalyzer - Collection was modified\Test.ps1: line 29
                        at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo :


Environment data

> $PSVersionTable

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

> (Get-Module -ListAvailable PSScriptAnalyzer).Version | ForEach-Object { $_.ToString() }

1.19.0
1.18.3
1.18.2
1.18.1
1.18.0
1.17.1

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:9

github_iconTop GitHub Comments

1reaction
mrboringcommented, Jun 13, 2020

Very nice work!

1reaction
bergmeistercommented, Jun 13, 2020

I found a better way of implementing option 2 by specifically catching the exception when it happens and then requesting a fresh, new object that does not come from the cache. Watch PR #1523 for that. Whilst errors were coming from multiple different sources, I found a more minimalistic repro that reliably reproduces as those cmdlet seem to be frequently the source of the errors:

1..100 | ForEach-Object { $null = Invoke-ScriptAnalyzer -ScriptDefinition @'
Get-Content
Test-Path
Get-ChildItem
Get-Content
Test-Path
Get-ChildItem
'@ -Settings @{ 'Rules' = @{ 'PSUseCorrectCasing' = @{ 'Enable' = $true } } } }
Read more comments on GitHub >

github_iconTop Results From Across the Web

Collection was modified; enumeration operation may not ...
Obviuosly, your do something code is trying to modify the collection. It's generally a bad idea to modify the collection while iterating on...
Read more >
Collection was modified; enumeration operation may not ...
I have tried dropping everything into the variable again (using "$computers = $computers" after removing the object) in the script block. The ...
Read more >
Why the error Collection was modified enumeration ...
This error occurs when a looping process is being running on a collection (Ex: List) and the collection is modified (data added or...
Read more >
enumeration operation may not execute Delete all libraries ...
You get this error because you're deleting straight from your source collection, which will change as soon as you start deleting.
Read more >
Exception "Collection was modified; enumeration operation ...
An exception with message "Collection was modified; enumeration operation may not execute" is shown when executing custom code.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found