January 31st, 2014

PowerTip: Learn to Use Where or ForEach in PowerShell 4.0

Doctor Scripto
Scripter

Summary: Learn the easy way to use Where or ForEach in Windows PowerShell 4.0.

Hey, Scripting Guy! Question I am running Windows PowerShell 4.0 and I want to know the easy way to use Where or ForEach.

Hey, Scripting Guy! Answer In Windows PowerShell 4.0, object arrays have a built-in .Where() and .ForEach() methods.
          You can use these methods to filter objects or perform operations with each object in the array.

For example, to use the Where() method to filter for a specific process name, run this command:

@(Get-Process).Where({ $PSItem.Name -eq ‘notepad’; }).

To iterate over a list of objects in an array and perform an operation against them by using the ForEach() method, run this command:

@(Get-Process –Name notepad).ForEach({ Stop-Process -InputObject $PSItem; }).

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.