Implicit Foreach in PSv3

PowerTip of the Day, from PowerShell.com:

PowerShell v3 Beta is available for quite some time now, so every now and then we start tossing in some PowerShell v3 tips. We’ll clearly mark them as such since they only run on PowerShell v3, not v2. This is something new in PowerShell v3:

When you work with array data, in previous PowerShell versions you had to loop through all elements to get to their properties and methods. No more in PowerShell v3. PowerShell now detects that you are working with an array and applies your call to all array elements. So with this line you could gracefully close all running notepad.exe.

(Get-Process notepad).CloseMainWindow()

Previously, you would have had to write:

Get-Process notepad | ForEach-Object { $_.CloseMainWindow() }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s