Windows PowerShell LoopsWindows PowerShell LoopsAutomating repetitive tasks is what scripting is all about. Therefore, each scripting language needs at least one method for cycling, or looping through a block of instructions. PowerShell provides a rich variety of looping techniques. However, because loops can go spectacularly wrong, I recommend you test a simple PowerShell loop before graduating to more complex constructions in your production scripts. Types of PowerShell Loop
While LoopsThe 'While' loop is the easiest to master, and also the most flexible. Each type of PowerShell loop has specific syntax rules; in the case of the 'While' loop there are only two elements (condition) and {Block Statement}. As so often with PowerShell, the type of brackets is highly significant; (Parenthesis for the condition) and {curly braces for the command block}. The way that the loop works is that PowerShell evaluates the condition at the start of each cycle, and if it's true, then it executes the command block. Here is a simple PowerShell 'while' loop to calculate, and then display, the 7 times table. $i
=7 Learning PointsNote 1: $i is a variable set to 7. Remember,
the mission was to create the seven times table. Alternatively, we could use a semicolon to join the two statements
to form one line. Do While LoopIn the 'Do ... While' loop, PowerShell checks the (condition) at the end of each loop. One feature of the 'Do While' loop is that the {Command Block} is always executed at least once, this is because the 'While' comes after the 'Do'. $i = 7; do { $i; $i +=7 } while ($i -le 85) Note 1: Without the semicolon it would need two lines thus: $i = 7
do { $i; $i +=7 } while ($i -le 85) Do Until $i = 7; do { $i; $i +=7 } until ($i -gt 85) Foreach Classic PowerShell Loop (3 Examples)The PowerShell 'ForEach' loop is more complex, and has more arguments than the 'for' and 'Do While'. The key feature is that loop interrogates an array, known as a collection. In addition to the position, and the type of bracket, observe the tiny, but crucial keyword, 'in'. Here is the syntax: ForEach ($item in $array_collection) {command_block} PowerShell Example 1 - Mathforeach ($number in 1,2,3,4,5,6,7,8,9,10,11,12 ) { $number * 7} foreach ($number in 1..12 ) { $number * 7} $NumArray = (1,2,3,4,5,6,7,8,9,10,11,12) foreach ($number in 1,2,3,4,5,6,7,8,9,10,11,12 ) { $number * 7} $NumArray = (1..12) Learning PointsNote 1: By creating five variations, my aim is to give you both perspective and experience of the PowerShell foreach loop. Note 2: (1..12) is a convenient method of representing a sequence. PowerShell Example 2 - To display filesHere is an example of a
PowerShell 'foreach' loop which displays the filename and its size. In order to get this example to work, create a cmdlet by saving the following into
a file, and give it a .ps1 extension. Call the cmdlet from the PS prompt. If the file is called ListDoc.ps1, and assuming that the file is in the current directory, then at the PS prompt type: Alternatively, from the PS prompt, type the full path D:\scripts\listdoc. Cmdlet 1 foreach ($file in get-Childitem) In Cmdlet 2 (below), we can employ a simple 'if' statement to filter .txt files. Naturally, feel free to alter -eq ".txt" to a more suitable extension. Cmdlet 2
# PowerShell foreach loop to display files LastAccessTime Learning PointsNote 0: If all else fails, copy the above code, and paste to PowerShell prompt, and then press 'Enter'. Note 1: `t means Tab.
˚
PowerShell Example 3 - Active DirectoryThis example conforms to the PowerShell ForEach (condition) {Code Block}; however, there is a preamble of 16 lines where the script connect to Active Directory. Moreover, the {Code Block} is spread over several lines. N.B. Find $Dom on line 7 and change the value to that of your domain, including the extension. # ForEach_AD.ps1 Learning PointsNote 1: ` on its own means word-wrap. `n means new line and `t means tab. PowerShell For Loop (Also know as the for statement)One use of the PowerShell 'For loop' is to iterate an array of values and then work with a subset of these values. Should you wish to cycle through all the values in your array, consider using a foreach construction. Here is the syntax: for (<init>; <condition>; <repeat>) {<command_block>} Example for ( $i = 7; $i -le 84; $i+=7 ) { $i } PowerShell Loop Output trickI have not found it possible to pipe input into loops. Obtaining output was nearly as difficult, however, I have discovered this trick to assign the output to a variable, which we can then manipulate.
$NumArray = (1..12) Dejan Milic's Method (Better)
$NumArray = (1..12) /\/\o\/\/'s Method (Fantastic)
$7x = 1..12 |% {$_ * 7 } I (Guy) envy /\/\o\/\/'s ability to write tight code. That % sign means 'foreach'. If you (readers) see anything on the internet by /\/\o\/\/, then you can be sure that it's top draw code. Summary of PowerShell LoopsPowerShell supports a variety of different loops, for example, 'While' and 'Foreach'. The secret of understanding the PowerShell loop is to study the type of bracket. For example when defining the constructions elements, (use parenthesis) for the condition and {use braces} for the command block. Take the time to master loops, and thus automate your repetitive tasks. See also PowerShell syntax• PowerShell Home • Syntax • Loops • Variables • What If • Functions • Replace Please write in if you see errors of any kind. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
*
|
||||||