foreach loop

The foreach loop is probably the most used loops. It will run through a defined collection and execute the script with a dynamic variable for each object in the defined collection. It is very handy when you need to do something with all of the values in a collection. The simple syntax looks as follows:

# simple syntax of a foreach-loop
# foreach ($<item> in $<collection>)
# {
# <statement list>
# }

You start off with the foreach keyword, followed by looping parentheses. Here, you start with $<item>, which is a not defined variable, followed by the in keyword and the collection that you want to loop through. After each execution of the statement, the dynamic variable will be filled up with the next object in the collection. Let's take a look at a simple example:

# simple example for a foreach-loop
$stringArray = 'Pow', 'er','Shell', 42
foreach ($obj in $stringArray)
{
Write-Host $obj
}
# 'Pow', 'er', 'Shell', '42'
It is important that you don't make any manipulations to the length of the looping collection, because this would result in an exception.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.205.223