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-Object

PowerShell Foreach-Object Cmdlet

Looping is core method for scripting.  About the only topic of confusion in PowerShell is that between the foreach operator and the Foreach-Object cmdlet.

In a nutshell if you need pipelining study this page.  If you want a quick easy method study the simple PowerShell loops here.

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-Object Cmdlet

 ♣

PowerShell's Foreach-Object Cmdlet

The Foreach-Object cmdlet specializes in controlling loops which accept pipeline input.  Another of this cmdlet's interesting features is the -begin and -end parameters.

Example 1: PowerShell Foreach-Object Cmdlet

The purpose of this script is to interrogate the Windows System event log, and then save the results to a file.

# PowerShell Foreach-Object
$LogPath = "C:\temp\system.txt"
$i = 0
$LogType = "System"
$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 1:  The key is element is piping the output from $Logs into the Foreach-Object cmdlet.  The script then extracts the $_.message from each item and writes it into a file.

Note 2:  To check my logic, you may wish to amend the values for $LogPath and $LogType to suit your computer.

Researching Parameters for Foreach-Object

Clear-Host
Get-Help Foreach-Object

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

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

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

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.

Comparison of PowerShell Foreach Operator with Foreach-Object Cmdlet

My take on the debate between the simple foreach operator and the more sophisticated Foreach-Object cmdlet is this: if in doubt start with plain foreach.  However, if you need piping, then stick with the cmdlet.  If execution speed is important, then read-up on which is better for your situation.

Speed Comparision

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 5: This script uses Measure-Command to compare PowerShell's two looping techniques.  See more on $_.property.

For Even More Information about Foreach Loops - Check About_Foreach

Clear-Host
Get-Help About_foreach

Summary of PowerShell Foreach-Object Cmdlet

The secret of understanding the PowerShell foreach-object is to focus on piping. Also observe that the plain foreach statement contains 'in'.  Finally, the cmdlet has parameters such as -begin.

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: