PSLambda icon indicating copy to clipboard operation
PSLambda copied to clipboard

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

Open SeeminglyScience opened this issue 7 years ago • 0 comments

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.

SeeminglyScience avatar Jun 01 '18 13:06 SeeminglyScience