Powershell – Declare Array and Iterate with ForEach

In Powershell, you can iterate through list of objects (or collection of objects) using ForEach loop. You can either initialize new array variable or get collection of objects from other cmdlet and store it in an array variable and iterate the array object using foreach loop function. You can also iterate collection of objects using ForEach-Object cmdlet.

Let’s declare array variable with list of string values:

$strArray = @("value1", "value2", "value3","value4")

Now, we can pass this array object to ForEach statement and get all the elements one-by-one and process it.

$strArray = @("value1", "value2", "value3","value4")
ForEach($str in $strArray) 
{
        Write-Host  "Processing the string element:" $str
}

You can also process the list of objects using ForEach-Object cmdlet.

$strArray = @("value1", "value2", "value3","value4")
$strArray | ForEach-Object {
        Write-Host  "Processing the string element:" $_
}

Although we can use both ForEach statement and ForEach-Object to return the same results, there are some differences between them regarding performance and usage. We can pass the output of ForEach-Object to next pipeline, but we can’t do this with foreach statement. The ForEach-Object cmdlet process each element as it passes through the pipeline, so it uses less memory, but foreach statement generates the entire collection before processing individual values.

Advertisement

Leave a Comment