For

Run a command block based on a conditional test.

Syntax
      for (init; condition; repeat) 
        {command_block}

Key

   init      Commands, separated by commas, to run before the loop begins.
             Typically used to initialize a variable with a starting value.
             The comma syntax does not work with multiple assignments, use a hash table instead.

   condition If this evaluates to TRUE the for loop {command_block} runs
             when the loop has run once the condition is evaluated again

   repeat    Commands, separated by commas, to run each time the loop repeats.

A typical use of the for loop is to operate on a subset of the values in an array.
In most cases, if you want to iterate all values in an array, consider using a foreach statement.

Examples

Count to 10:

 PS> for($i=1; $i -le 10; $i++){Write-Host $i}

You can use carriage returns instead of semi-colons:

 PS> for($i=1
     $i -le 10
     $i++ ){
     Write-Host $i
     }

Incrementing two variables:

For ($demo = @{"a"=0;"b"=50}; $($demo.a) -le10; $demo.a++, $demo.b++) {
   Write-Host "a:$($demo.a) b:$($demo.b)" -foregroundcolor green
   }

“An essential aspect of creativity is not being afraid to fail” ~ Edwin Land

Related PowerShell Cmdlets

Break statement
Continue statement
Comparison operators -like, -lt, -gt, -eq, -ne, -match
ForEach - Loop through values in the pipeline.
IF - Conditionally perform a command.
While Loop while a condition is True.


 
Copyright © 1999-2024 SS64.com
Some rights reserved