Author Posts

August 24, 2015 at 8:32 pm

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++)
{ }

August 24, 2015 at 8:38 pm

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

August 24, 2015 at 9:06 pm

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

August 25, 2015 at 1:27 am

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

you can use

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

or

while ( ... ) { ... }

August 25, 2015 at 3:27 am

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

August 25, 2015 at 3:50 am

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

August 25, 2015 at 3:56 am

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

August 25, 2015 at 4:57 am

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

This helped me a lot

& it is certainly knowledgeable
🙂