Using multiple commands in the <init> part of a Powershell for loop

Viewed 81

I get an error when trying to use multiple commands in the <Init> part of a for loop in Powershell. For example,

function Example {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)] [int] $Base,
        [Parameter(Mandatory=$True)] [int] $Count
    )
    Process {        
        for ( $item = 1, $id = $Base; $item -le $Count; $id++, $item++ ) {
        }
    }
}

Example -Base 1 -Count 2

The Microsoft documentation says that <Init> "represents one or more commands" and that <Repeat> "represents one or more commands, separated by commas". The wording is different, so I realize that the syntax may be different.

The error I get is "The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property." with the underscore beneath the 1 in "$item = 1".

1 Answers

You have to wrap the <init> component of your for loop either with Subexpression operator $(..):

for($($item1 = 0; $item2 = 10); $item1 -lt 10 -or $item2 -gt 0; $item1++, $item2--) {
    [pscustomobject]@{
        item1 = $item1
        item2 = $item2
    }
}

Or, as Abraham points out in his comment, each variable assignment wrapped with parentheses: ($item1 = 0), ($item2 = 10).

Following your example function, this should work:

function Example {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory)]
        [int] $Base,

        [Parameter(Mandatory)]
        [int] $Count
    )

    Process {
        for (($item = 1), ($id = $Base); $item -le $Count; $id++, $item++) {
            [pscustomobject]@{
                item = $item
                id   = $id
            }
        }
    }
}

Example -Base 4 -Count 10
Related