Taking on PowerShell one cmdlet at a time

Share this post:This blog post is part of an ongoing series by Adam Gordon. Adam will walk through each PowerShell command every week, explaining when and how to use them. Adam will be covering ForEach-Object this week.

When to use ForEach Object
The ForEachObject cmdlet performs an operation for each item in a set of input objects. The input objects can either be piped to this cmdlet, or specified using the -InputObject parameter.
There are two ways to create a ForEach object command in Windows PowerShell 3.0.
Script block. The $_ variable is used to represent the current object within the script block. The script block is the value for the -Process parameter. Any PowerShell script can be contained in the script block.
Operation statement. An operation statement can also be written, which is more natural than natural language. The operation statement can be used to specify a property value, or call a method.

How to use ForEach Object
Divide integers into an array:
32070, 546208, 121233452 | ForEach-Object -Process $_/1024
This command takes an array with three integers and divides them by 1024.

Find the names of all files in a directory.
Get-ChildItem $pshome | ForEach-Object -Process if (!$_.PSIsContainer) $_.Name; ” ”
This command retrieves the files and directories from the PowerShell installation directory $pshome, and passes them on to the ForEach Object cmdlet.
If the object isn’t a directory, the script blocks gets the file name and adds a space (“”) to seperate it from the next entry.
The cmdlet uses PSISContainer to determine if an object is a directory.

Operate on the most recent System events
$Events = Get-EventLog -LogName System -Newest 3000
$Events | ForEach-Object -Begin Get-Date -Process Out-File -FilePath C:\PShellTest\Events.txt -Append -InputObject $_.Message -End Get-Date
This command retrieves the 3000 most recent events in the System event log and stores them into the $Events variable. The event data is then piped to the ForEachObject cmdlet.
The -Begin parameter displays current date and times.
Next, the –Process parameter uses Out-File to create a textfile named Events.txt. It stores each event’s message property in that file.
The -End parameter displays the date and time after processing is complete.

Learn the command for last week: Where-Object.
Do you need PowerShell training? ITProTV offers PowerShell online IT training courses.