Implicit Foreach in PSv3

by Jun 8, 2012

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.

PS> (Get-Process notepad).CloseMainWindow()

Previously, you would have had to write:

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

Twitter This Tip! ReTweet this Tip!