Skip to content

Nested foreach statements throw when the enumerator is of a different type #20

Description

@SeeminglyScience

Example code:

[psdelegate]{
    foreach ($a in 0..10) {
        foreach ($b in 'one', 'two') {
            $Host.UI.WriteLine($a.ToString() + $b.ToString())
        }
    }
} | % invoke

Throws

% : Exception calling "Invoke" with "1" argument(s): "At line:3 char:9
+         foreach ($b in 'one', 'two') {
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expression of type 'System.Collections.Generic.IEnumerator`1[System.String]' cannot be used for assignment to type 'System.Collections.Generic.IEnumerator`1[System.Int32]'"
At line:7 char:5
+ } | % invoke
+     ~~~~~~~~
+ CategoryInfo          : InvalidOperation: (PSLambda.PSDelegate:PSObject) [ForEach-Object], MethodInvocationException
+ FullyQualifiedErrorId : MethodInvocationError,Microsoft.PowerShell.Commands.ForEachObjectCommand

I'm probably reusing a variable somewhere I shouldn't when constructing the loop. Work around is to use the System.Linq.Enumerable extension methods, Array.ForEach (or similar), or a for statement.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions