concept foreach loop in category powershell

appears as: foreach loop, The foreach loop
Windows PowerShell in Action, Third Edition

This is an excerpt from Manning's book Windows PowerShell in Action, Third Edition.

This causes the most problems for people when they use hashtables in the foreach statement. In a .NET language like C#, the foreach statement iterates over all the pairs. In PowerShell, the foreach loop will run only once because the hashtable isn’t considered an enumerable, at least not by default. If you want to iterate over the pairs, you’ll have to call the GetEnumerator() method yourself:

Using the for loop is straightforward, but managing the loop counter becomes annoying because it involves writing more code than other loop structures. The foreach loop, by comparison, lets the loop counter count take care of itself, so let’s move on.

First you set the variable that will hold the total length to 0. Then, in the foreach loop, you use the Get-ChildItem command to get a list of the text files in the current directory. The foreach statement assigns elements from this list one at a time to the loop variable $f and then executes the statement list with this variable set. At the end of the statement, $f will retain the last value that was assigned to it, which is the last value in the list. Compare this example to the for loop examples in the previous section. Because you don’t have to manually deal with the loop counter and explicit indexing, this example is significantly simpler.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage