PowerTip: Learn to Use Where or ForEach in PowerShell 4.0

The Scripting Guys

Dr Scripto

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; }).

The Scripting Guys
Dr Scripto

Follow Dr Scripto   

No Comments.