PowerTip: Learn to Use Where or ForEach in PowerShell 4.0


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

Comments (8)

  1. Anonymous says:

    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?

  2. Mike here says:

    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

  3. David Wyatt says:

    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’ })

  4. jrv says:

    @Chris – learn to apply Lewis Carroll logic to this. Enumerate! Don’t obfuscate. @{‘thing1′,’thing2’} | %{$_}

  5. Boe Prox says:

    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/

  6. Chris says:

    Does this work an array? @("thing1", "thing2") If so, what is the syntax? Me being a noob, I’m not figuring it out.

  7. jan says:

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

  8. nicolas says:

    Thanks

Skip to main content