Guy recommends :
Free SolarWinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



PowerShell Foreach Loops

PowerShell Foreach Operator Loops

For me, one of the most magical aspects of scripting is how simple code loops through a set of instructions and then produces results - in a flash.  Sometimes this magic is hidden, for example Get-Process implies looping as it returns all the running processes, in other cases we need foreach to explicitly call for PowerShell to step through the items.

My mission on this page is to give you simple examples on how to master the PowerShell foreach loop.  As you become more proficient in PowerShell, so the instructions grow in complexity.

Topics for PowerShell's Foreach Loop

 ♣

Examples of the PowerShell Foreach Loop

Each loop interrogates an array, which is known as a collection.  During each cycle the foreach operator executes a {Statement Block}. 

Note that when working with PowerShell examples the brackets always carry hidden messages.  Observe that the (array enclosed by parenthesis brackets), while the block statement is always contained in {Curly brackets}.

One more tiny, but crucial, component of the PowerShell foreach loop is 'in'.

The secret of understanding this PowerShell loop syntax is to absorb each element of this syntax:
Foreach ($item in $array_collection) {command_block}.

Example 1: PowerShell Foreach with Pure Math

# Simple PowerShell foreach statement
foreach ($number in 1,2,3,4,5,6,7,8,9,10) { $number * 13}

# PowerShell Foreach Example
Clear-Host
foreach ($number in 1..10 ) { $number * 13}

Clear-Host
$NumArray = (1,2,3,4,5,6,7,8,9,10)
foreach ($number in $NumArray ) { $number * 13}

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

Clear-Host
$NumArray = (1..10)
foreach ($number in $numArray ) { $number * 13}

Learning Points

Note 1:  By creating these five variations, my aim is to give you both perspective and experience of the pure, but simple PowerShell foreach statement.

Note 2:  Foreach is at the start of its command line (unlike Foreach-Object).

Note 3:  PowerShell's 'Foreach' is more complex, and has more arguments than the 'for' and 'Do While' techniques for stepping through a collection of items. 

Example 2:  PowerShell Foreach to Display Files

In Example 2 we are going to transition from the explicit ($Item in Collection) {Block Statement} to:
Input stuff using Get-ChildItem, then pipe (|) the output into a {Block Statement}.

Get-ChildItem is just the vehicle for us to investigate aspects of the PowerShell foreach loop.  I chose the root of the C: drive simply because this example script will work without modification on most of computers.

Example 2a Explicit Foreach Get-ChildItem

# PowerShell Foreach File Example
Clear Host
Foreach ($file in Get-Childitem C:\)
{
$file.name
}

Example 2b Foreach Piping | Directly Into the {block statement}

As usual with scripting PowerShell has dozens of techniques to achieve the same outcome.  The key difference in this example is how the foreach works with input from PowerShell's piping.  The point is that there is no need for an explicit ($Item in $Collection) clause.

# PowerShell Foreach File Example
Clear Host
$Path = "C:\Windows\System32\*.dll"
Get-ChildItem $Path | Foreach {
Write-Host $_.Name
}

Learning Points

Note 4:  To help modify my scripts to suit your project I have introduced a $Path variable.  See more on the $_. construction.

Guy Recommends:  SolarWinds' Free Bulk Import ToolFree Download of Solarwinds  Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click to import the users.  Optionally, you can provide the name of the OU where the new accounts will be born.

There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import tool.

Example 3: A More Complex Foreach Example

This pair of examples are just like the above, but introduce slightly more complex scripting.  Example 3a contains Foreach with a ($Item in Collection) clause; please contrast with example 3b which exploits the ability of foreach to receive input via the pipe (|).

# PowerShell foreach loop to display files in C:\Program files
$Path = "C:\Program Files\"
"{0,10} {1,-24} {2,-2}" -f `
" Size", "Last Accessed", "File Name "
Foreach ($file in Get-Childitem $Path -recurse -force)
{If ($file.extension -eq ".txt")
   {
   "{0,10} {1,-24} {2,-2}" -f `
   $file.length, $file.LastAccessTime, $file.fullname
   }
}

Example 3b Foreach piping | directly into the {block statement}

# PowerShell foreach loop piping into block statement
Clear-Host
$Path = "C:\Program Files\"
Get-Childitem $Path -recurse -force | Foreach {
If ($_.extension -eq ".txt") {
Write-Host $_.fullname
    }
}

Note 5: This example uses the same 'If clause' as example 3a, its purpose is to filter just .txt files.

Example 4: PowerShell Foreach Loop With WMI

Once again, observe the basic structure: Foreach (x in y) {script block}.  Where you have more than one drive you need a loop, in this case the foreach loop.

Basic Example

$disk= Get-WmiObject Win32_LogicalDisk
Foreach ( $drive in $disk ) { "Drive = " + $drive.Name}

Example Incorporating Extra Maths

# Foreach example to display the partitions size [GB]
$disk= Get-WmiObject Win32_LogicalDisk
"Drive Ltr: Size [GB]"
Foreach ( $drive in $disk ) { "Drive = " + $drive.Name + `
" Size = " + [int]($drive.Size/1073741824)}

Guy Recommends: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.  Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server.

Download your free copy of WMI Monitor

Example 4: Another Simple Foreach Using Get-Process

Here is an example using Get-Process.  In essence this simple script filters the running processes.  Please feel free to modify.  Once again, note the tiny word 'in'.

# PowerShell example listing processes beginning with Task*
Clear-Host
Foreach ($T in Get-Process Task*)
{$T.Name}

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 * 13}) | set-variable 13x
$13x
# Option research properties by removing # on the next line
# $13x |Get-Member

Dejan Milic's Method (Better)

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

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

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

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.

For Even More Information about Foreach Loops - Check About_Foreach

Clear-Host
Get-Help About_foreach

PowerShell's Foreach-Object Cmdlet

The Foreach-Object cmdlet specializes in controlling loops which accept pipeline input.  One of this cmdlet's interesting features is displaying start and finish times.  It achieves this courtesy of the -begin and -end parameters.

Confusion: What adds to the confusion is that the Foreach-Object cmdlet has an alias of foreach.  My tip is watch out for the use of 'in', which is used by foreach the statement, the operator, but not by Foreach the alias for the cmdlet.  The key technical difference is the Foreach-Object does not have to be the first item in the statement, and more importantly, it accepts | (pipelining).

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v10

SolarWinds' Orion performance monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

Perhaps the NPM's best feature is the way it suggests solutions to network problems.  Its second best feature is the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you take advantage of SolarWinds' offer.

Download a free trial of the Network Performance Monitor.

Example 5: PowerShell Foreach-Object Cmdlet

In addition to plain foreach, which is an operator, PowerShell has a Foreach-object cmdlet.

The purpose of this script is to interrogate the application event log.

$LogPath = "C:\temp\application.txt"
$i = 0
$LogType = "Application"
$Logs = Get-Eventlog -logname $LogType -newest 500
$Logs | Foreach-Object {
Out-File -filepath $LogPath -append -inputobject $_.message; $i++
}
Write-Host "$i $LogType logs written to $LogPath"

Note 7:  The key is element is piping the $Logs into Foreach-Object, then referencing $_.message

Note 8:  You may wish to amend the values for $LogPath and $LogType.

$LogPath = "C:\temp\application.txt"
$i = 0
$LogType = "Application"
$Logs = Get-Eventlog -logname $LogType -newest 500
$Logs | Foreach-Object -begin {Get-Date} -process {
Out-File -filepath $LogPath -append -inputobject $_.message; $i++
} -end {Get-Date}
Write-Host "$i $LogType logs written"

Note 9:  Observe how the -begin and -end parameters write date stamps.

More Information on Foreach-Object

Clear-Host
Get-Help Foreach-Object

Note 10: The Foreach-Object has this alias: % (Percent sign)

Comparison of PowerShell Foreach Operator with Foreach-Object Cmdlet

It surprised me that the simple foreach operator was an order of magnitude faster than the Foreach-Object cmdlet.

# Comparision of PowerShell foreach operator and Foreach-object cmdlet
Clear-Host
$BigNum = 1..10000
$GuyMuliplier = 7777
Write-Host "Foreach operator. Note command uses word 'in'."
Measure-Command {foreach($item in $BigNum) {$item*$GuyMultiplier}} `
| Format-Table Milliseconds -auto
Write-Host "Foreach-Object Cmdlet. In the code, note the pipe"
Measure-Command {$BigNum | Foreach {$_ * $GuyMultiplier} } `
| Format-Table Milliseconds -auto

Note 11: This script uses Measure-Command to compare PowerShell's two looping techniques.

Summary of PowerShell Foreach Loops

The secret of understanding the PowerShell foreach 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.

In addition to Take the time to master loops, and thus automate your repetitive tasks.

If you like this page then please share it with your friends

 


See more PowerShell examples

PowerShell Home   • Foreach loops   • PowerShell Foreach   • Foreach-Object cmdlet

Syntax   • Variables   • -whatIf   • -ErrorAction   • Windows PowerShell   • PowerShell 2.0

PowerShell Functions   • [System.Math]   • Get-Credential   • Windows 7 PowerShell 2.0

Please email me if you have a better example script.  Also please report any factual mistakes, grammatical errors or broken links, I will be happy to  correct the fault.

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.

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, SolarWinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2012 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: