PowerShell


Windows PowerShell Loops

Windows PowerShell Loops

Automating 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 loop before graduating to more complex loops in your production scripts.

Types of PowerShell Loops

While Loops

The '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 loop to calculate, and then display, the 7 times table.

$i =7 # Set variable to zero
while ($i -le 85) { $i; $i +=7}

Learning Points

Note 1:  Observe the two types of bracket (while) {Block Calculation}
Note 2: -le means less than or equals.
Note 3: +=7 increments the variable $i by seven on each loop.

Alternatively, we could use a semi colon to join the two statements to form one line.
$i =7;  while ($i -le 85) { $i; $i +=7 }.

Do While Loop

In the 'Do ... While' loop, PowerShell checks the (condition) is 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)

Do Until
There is a variation of this style of loop, 'Do .. Until'.  The layout of the components is the same as 'Do While', the only difference is that the logic is changed from, do while condition is true, to, do until condition is true.

$i = 7; do { $i; $i +=7 } until ($i -gt 85)

Foreach Loop in PowerShell (3 Examples)

The '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}

Example 1 - Math

foreach ($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 $numArray ) { $number * 7}

foreach ($number in 1,2,3,4,5,6,7,8,9,10,11,12 ) { $number * 7}

$NumArray = (1..12)
foreach ($number in $numArray ) { $number * 7}

Learning Points

Note 1:  By creating five variations, my aim is to give you perspective and experience of the foreach loop.

Note 2:  (1..12) is a convenient method of representing a sequence.

Example 2 - To display files

Here is an example of a '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:
.\listdoc

Alternatively, from the PS prompt, type the full path D:\scripts\listdoc.

Cmdlet 1

foreach ($file in get-Childitem)
{
$file.name + " " +$file.length
}

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 cmdlet to display files LastAccessTime
"File Name " + "`t Size" +"`t Last Accessed"
foreach ($file in get-Childitem)
{if ($file.extension -eq ".txt")
    {
     $file.name + "`t " +$file.length + "`t " +    $file.LastAccessTime
    }
}

Learning Points

Note 0:  If all else fails, copy the above code, and paste to PowerShell prompt, and then press 'Enter'.

Note 1: `t means Tab.

  ˚

Example 3 - Active Directory

This example conforms to the 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
# Illustrates using ForEach loop to interrogate AD
# IMPORTANT change $Dom 'value'
# Author: Guy Thomas
# Version 2.5 November 2006 tested on PowerShell RC2

$Dom = 'LDAP://DC=YourDom;DC=YourExt'
$Root = New-Object DirectoryServices.DirectoryEntry
cls

# Create a selector and start searching from the Root of AD
$selector = New-Object DirectoryServices.DirectorySearcher
$selector.SearchRoot = $root

# Filter the users with -like "CN=Person*". Note the ForEach loop
$adobj= $selector.findall() `
| where {$_.properties.objectcategory -like "CN=Person*"}
ForEach ($person in $adobj)
{
$prop=$person.properties
      Write-host "First name: $($prop.givenname) " `
      "Surname: $($prop.sn) User: $($prop.cn)"
}
write-host "`nThere are $($adobj.count) users in the $($root.name) domain"

Learning Points

Note 1: ` on its own means word-wrap.  `n means new line and `t means tab.

For Loop (Also know as the for statement)

One use of the '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 trick

I 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)
$(foreach ($number in $numArray ) { $number * 7}) | set-variable 7x
$7x
# Option research properties by removing # on the next line
# $7x |get-Member

Dejan Milic's Method (Better)

$NumArray = (1..12)
$7x = @()
foreach ($number in $numArray ) { $7x+=$number * 7}
$7x

/\/\o\/\/'s  Method (Fantastic)

$7x = 1..12 |% {$_ * 7 }
$7x

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 Loops

PowerShell supports a variety of different loops, for example, 'While' and 'Foreach'.  Brackets play a vital role in defining the elements syntax, (use parenthesis) for the condition and {use braces} for the command block. Take the time to master loops and thus automate repetitive tasks.

See also PowerShell syntax

PowerShell Home   • Syntax   • Loops   • Recursive  • 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.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Google

WebComputerperformance.co.uk

 

Home Copyright © 1999-2008 Computer Performance LTD All rights reserved

Please report a broken link, or an error.