for loop in powershell with 2 variables

This topic contains 7 replies, has 4 voices, and was last updated by  Harshall mankar 2 years ago.

  • Author
    Posts
  • #28935

    Harshall mankar
    Participant

    hello
    i need to write for loop like below in powershell please help me with that

    for(int i=0,int j=0; i<6,j<5;i++,j++)
    { }

  • #28937

    Don Jones
    Keymaster

    Sorry, that makes no sense to me. Can you explain your goal? Do you mean you need two nested loops?

  • #28938

    Harshall mankar
    Participant

    no i don't want nested loop i want to have 2 variables as part of for loop "i & j" this is allowed
    other programming language

    for(int i=0,int j=0; i<6,j<5;i++,j++)

    this means i want to have i & j variables in single for loop not nested

  • #28942

    Max Kozlov
    Participant

    and what value for j will be when i=5 in your loop ?

    you can use

    $i=$j=0
    do { ... } while ( ... )

    or

    while ( ... ) { ... }

  • #28945

    Dave Wyatt
    Moderator

    You can do this in PowerShell, but it requires the use of the subexpression operator so the parser knows what's happening:

    for ($($i = 0; $j = 0); $i -lt 6; $($i++; $j++))
    {
        "I: $i, J: $j"
    }
    
  • #28947

    Max Kozlov
    Participant

    btw, parser be happy not only with $() but with @() too and even with array assign exotic:

    PS C:\> for (
    >>> ($i,$j)=(0,10)
    >>> $i -le $j
    >>> @( $i++, $j--) ) {
    >>> "$i - $j"
    >>> }
    0 - 10
    1 - 9
    2 - 8
    3 - 7
    4 - 6
    5 - 5

    Dave, your example contains only one exit condition and Harshalls' – two.
    This take my mind...

  • #28948

    Dave Wyatt
    Moderator

    Ah, missed that. For the condition, just join them with an -and:

    for ($($i = 0; $j = 0); $i -lt 6 -and $j -lt 5; $($i++; $j++))
    {
        "I: $i, J: $j"
    }
    
  • #28950

    Harshall mankar
    Participant

    That was so helpful thanks @dave Wyatt & @Max Kozlov

    This helped me a lot

    & it is certainly knowledgeable
    🙂

You must be logged in to reply to this topic.