# PowerShell 2.0 version of Foreach-Object Clear-host $Prog
=Get-ChildItem 'C:\program files\*.*' -recurse Measure-Command
{$Prog | Foreach-Object {$_.name}}
Result Check for yourself, but assume it takes 100
Milliseconds. I am willing to wager the foreach statement in the
second example below will
be 10 times quicker.
My result 170 ms.
Incidentally, you could use this alias substitution: % {$_.name}
Guy Recommends: A Free Trial of the Network Performance Monitor
(NPM)
SolarWinds'
Network 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.
What I like best is the way NPM suggests solutions to network
problems. Its also has 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 try NPM now.
The whole rationale of
scripting is speed up manual operations. Thus, one of the key elements
is looping through a set of instructions while applying a script block to
each item.
PowerShell 3.0 loops have simpler syntax compared with versions 1 and 2.
As a result beginners can create loops more easily, yet old-timers can
reiterate using the same constructions they used in PowerShell 1.0.
Recap of
PowerShell's Foreach Loop
Let us examine the PowerShell 2.0 loop syntax:
Foreach ($item in $collection-array) {command_block}.
Foreach is the PowerShell instruction to cycle or repeat; it feeds on an
array of ($items in $collection-array) then you need a {Block statement
payload}.
One more tiny, but crucial, component of the PowerShell foreach loop is
'in'.
Simple PowerShell Foreach
# PowerShell Foreach Example
Clear-Host foreach ($number in 1..10 ) { $number *
25}
In PowerShell 3.0 the Where-Object and Foreach-Object have made a set
of {Curly} brackets optional. The idea is to make the scripts easier
to write for beginners. However, you will notice many old-times
still use the version 2.0 fuller syntax.
If you like this page then please share it with your friends
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.
Windows Management Instrumentation (WMI) is
most useful for PowerShell scripting.
SolarWinds
have produced this
Free WMI Monitor to take the guess work out of which
WMI counters to use for applications like Microsoft Active Directory,
SQL or Exchange Server.