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

Time:02-04

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".

CodePudding user response:

This is a bit unusual to see in a for loop, but I guess you mean something like this:

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

Note that in this example, you have to wrap the <init> component either with $(..) 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
  •  Tags:  
  • Related