PowerTip: Learn to Use Where or ForEach in PowerShell 4.0

PowerTip: Learn to Use Where or ForEach in PowerShell 4.0

  • Comments 8
  • Likes

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

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Does this work an array? @("thing1", "thing2") If so, what is the syntax? Me being a noob, I'm not figuring it out.

  • @Chris - learn to apply Lewis Carroll logic to this. Enumerate! Don't obfuscate. @{'thing1','thing2'} | %{$_}

  • Yep, the new syntax can be used on any array (and probably any IEnumerable object as well, though I haven't thoroughly tested it yet): @("thing1", "thing2").Where({ $_ -like '*2' })

  • I wrote an article a couple months ago that dives into .Where() and .ForEach() to include additional options which are available. http://learn-powershell.net/2013/11/26/checking-out-the-where-and-foreach-operators-in-powershell-v4/

  • This is cool. I'll admit that. But sheesh, I thought I was just finally getting sort of good with PowerShell and this version 4 seems like a whole new language, with Desired State Configs and the like LOL

  • After reading Boe Prox's article we see that these methods differ from using pipeline in one way by loading entire collection into memory. Is there a general rule as to how large this collection can or should be?

  • tnx a lot. it was very helpful for me.
    http://www.mashhadsite.com/">طراحی سایت در مشهد

  • Thanks