PowerShell: Iterate Array
here's ways to iterate over Array
ForEach-Object (cmdlet)
ForEach-Object
cmdlet
is most useful when you need to
Pipe
a collection to it.
(ForEach-Object
has alias %
, foreach
)
syntax:
ForEach-Object ScriptBlock
1..7 | ForEach-Object {$_}
Foreach (statement)
foreach-statement must be on a single line, when used in PowerShell prompt.
$aa = 1..9 foreach ($x in $aa) { echo $x } # prints 1 to 9
ForEach (PowerShell Intrinsic Method)
ForEach
is a hidden “intrinsic member” that PowerShell adds to every object.
syntax:
arrayX.ForEach(script_block)
iterate over array. In the script block, $_
is the value of current element.
$aa = 0..3 $aa.foreach({$_ + 1})
for (statement)
$aa = 1..9 for ($i=0; $i -le $aa.length; $i++) { $aa[$i] } # prints 1 to 9
while (statement)
$aa = 1..9 $i = 0; while ($i -lt 5) { Write-Host $aa[$i]; $i++ } # prints 1 to 5
PowerShell. Loop, Iteration
PowerShell. Array
- PowerShell: Array
- PowerShell: Array Sub-Expression Operator, Collection to Array
- PowerShell: Array and Types
- PowerShell: Nested Array, Multi-Dimensional Array
- PowerShell: Array, Get Item
- PowerShell: Array, Set Item
- PowerShell: Test If Collection Contains a Value
- PowerShell: Join Array, Append
- PowerShell: Filter Array (Where-Object)
- PowerShell: Delete Array, Clear Array
- PowerShell: Array to String
- PowerShell: Array Methods
- PowerShell: Iterate Array