about_Foreach.help - TOPIC about_Foreach SHORT DESCRIPTION...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Sheet1 Page 1 TOPIC about_Foreach SHORT DESCRIPTION Describes a language command you can use to traverse all the items in a collection of items. LONG DESCRIPTION The Foreach statement (also known as a Foreach loop) is a language construct for stepping through (iterating) a series of values in a collection of items. The simplest and most typical type of collection to traverse is an array. Within a Foreach loop, it is common to run one or more commands against each item in an array. Syntax The following shows the Foreach syntax: foreach ($<item> in $<collection>){<statement list>} The Foreach Statement Outside a Command Pipeline The part of the Foreach statement enclosed in parenthesis represents a variable and a collection to iterate. Windows PowerShell creates the variable ($<item>) automatically when the Foreach loop runs. Prior to each iteration through the loop, the variable is set to a value in the collection. The block following a Foreach statement {<statement list>} contains a set of commands to execute against each item in a collection. Examples For example, the Foreach loop in the following example displays the values in the $letterArray array. $letterArray = "a","b","c","d" foreach ($letter in $letterArray) { Write-Host $letter } In this example, the $letterArray array is created and initialized with the string values "a", "b", "c", and "d". The first time the Foreach statement runs, it sets the $letter variable equal to the first item in $letterArray ("a"). Then, it uses the Write-Host cmdlet to display the letter a. The next time through the loop, $letter is set to "b", and so
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Sheet1 Page 2 on. After the Foreach loop displays the letter d, Windows PowerShell exits the loop. The entire Foreach statement must appear on a single line to run it as a command at the Windows PowerShell command prompt. The entire Foreach statement does not have to appear on a single line if you place the command in a .ps1 script file instead. Foreach statements can also be used together with cmdlets that
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 11/03/2010 for the course BUS fin taught by Professor Fez during the Spring '10 term at Valparaiso.

Page1 / 5

about_Foreach.help - TOPIC about_Foreach SHORT DESCRIPTION...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online