PowerShell Iterate Over Array

By Xah Lee. Date: . Last updated: .

here's ways to iterate over Array

Array Method: ForEach

ForEach method is useful when you want to go thru all the values of array.

arrayX.ForEach(script_block)
iterate over array. In the script block, $_ is the value of current member.
$arr = 0..3
$arr.foreach({$_ + 1})
arrayX.ForEach(property_name_str)
list each element's property.
@(dir).foreach("lastAccessTime")
arrayX.ForEach(property_name_str, new_val)
set each element's property to a new value.
arrayX.ForEach(method_name_str)
call a method on each element.
@(dir -name).foreach("toUpper")

PowerShell Statement: Foreach

foreach statement is useful when you want to go thru all the values of array or collection.

foreach statement must be on a single line, when used in PowerShell prompt.

$arr = 1..9
foreach ($x in $arr) { echo $x }
# prints 1 to 9

ForEach-Object Cmdlet

ForEach-Object cmdlet (alias %, foreach) can be used by piping array to it.

ForEach-Object ScriptBlock
( 1..7 ) | ForEach-Object {$_}

PowerShell

Practical How-To

PowerShell in Depth

Programing PowerShell

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples