Search code examples
powershellforeachrange

Loop range with steps


I'm trying to move from BATCH into PowerShell and I am trying to convert my own scripts.

My problem is with ranges in loop: my original BATCH script was like

   for /L %%U in (123,2,323) do ECHO %%U

and will print

123
125
127
...

with Powershell a range would be 123..323, thus

123..323 | % {Echo $_ }

Will give me

123
124
125
...

Is there a way to set a range with a step that is different than 1? All the examples I find either list all the numbers (I have hundreds...) or use the two points between the numbers.


Solution

  • Simple Google search should have found you this.

    for ($i=123; $i -le 323; $i=$i+2 ) {Write-Host $i;}
    

    (Initialize; condition to keep the loop running; iteration)