CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – For and ForEach loop

PowerShell for loops are used to navigate within the collection to retrieve its elements and allow it to execute the statements within it continuously when the given condition is met.

Through this article, we are going to discuss For and ForEach loops.

The for loop in PowerShell

PowerShell for loop is used to execute the statements within it repeatedly until the given condition is False.  Unlike While loops; For loop is constructed with a compound structure containing 3 parts; each part is separated by a semi-colon (“;”).

Usually, the first part is for initialization and will execute when entered into a loop. Then the second part, a conditional expression will evaluate to execute the statements in the For loop. The loop exits, when this conditional expression returns the value, False. Finally, the last part will execute for every iteration of the loop.

The statements within for loop should be enclosed in curly braces (“{” and “}”). These statements will execute if the conditional expression is True.

Let’s take a simple example, counting the number of spaces in a string;

# for loop, identify number of spaces in the string
#
$str = "PowerShell scripting language!"
$spaces = 0

for ($idx = 0 ; $idx -lt $str.length ; $idx++ )
{
	if ( $str[$idx] -eq ' ' )
	{
		$spaces++;
	}
}

echo "Number of spaces found: "
echo $spaces

Observe, how we used the for loop to iterate through the string. $idx = 0, is in the initialization part. Conditional expression verifies whether the index value is within the boundary ($str.length returns the length of the string). $idx++ is in 3rd part, which increments the value of the index by 1 to help to navigate within the string.

The foreach loop in PowerShell

Unlike other loops, this loop works on collections. This allows traversing within the collection to retrieve its elements. One great advantage of foreach loop is, we do not need to worry about boundary checks, like what we do in other loops. It iterates through the collection and exits when all elements are iterated.

Let’s take a simple example, which iterates through the Hash table, to display its Key & Value pairs;

# foreach loop, to traverse within the hash table
#
$hash = @{A = "Apple"; B = "Berkshire Hathaway"; C = "Cisco"; D = "Deloitte"}

foreach ($ele in $hash)
{
	echo $ele
}

Observe, how easy it is to navigate within the collection using foreach loop. There is no code required for bounds checking; foreach loop automatically takes care of it.

Note that in is a keyword we use in ForEach loop; and the comparison operator -in , we use to compare the values or variables. Note this difference between in & -in.

[..] David

PowerShell – For and ForEach loop

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top