A Series of Items

Iterating Through an Array

To assist you with iteration, PowerShell provides a command let named ForEach-Object. The formula to use it is:

list | ForEach-Object {
    statement-1
    statement-2
    . . .
    statement-x
}

To use this command-let, precede it with a list such as an array. Separate the list and the command-let with a pipe operator. After the command-let, create a body delimited by curly brackets. In the body of the command-let, you can access every item of the list. To make this possible, PowerShell provides an object named $_. Here is an example:

$numbers = @(102, 44, 525, 38, 6, 28, 24481, 327, 632, 104)

$numbers | ForEach-Object {
    Write-Host "Number:" $_
}

Write-Host '==============================='

Alternative to the $_ object is an object named $PSItem. You can use it the same way we did with the other. Here is an example:

$numbers = @(102, 44, 525, 38, 6, 28, 24481, 327, 632, 104)

$numbers | foreach-object {
    Write-Host "Number:" $PSItem
}

Write-Host '==============================='

Previous Copyright © 2001-2025, FunctionX Wednesday 12 February 2025, 16:36 Next