Quick Tip - Split A PowerShell Collection Into Two Arrays

Did you know that you can use Where-Object to split a collection into two arrays? Like, if you had an array containing the numbers 1 to 10, you could split it into one array of even numbers, and another array of odd numbers? It’s pretty cool. Thanks Herb Meyerowitz for this tip!

As you can tell from Herb’s comment in this screenshot, it’s actually the .where() method that is relatively new that we’re using to split collections this way. The syntax is kind of atypical, so let’s break it down.

$a, $b = (1..5).where({$_ % 2}, 'split')
  • $a, $b = 
    • This part is creating two variables, named a and b that will be used to contain the output of our splitting activity.
  • (1..5)
    • This just creates an array of the numbers 1 through 5.
  • .where( )
    • This is a method that comes with PowerShell 5 (I'm pretty sure) which works mostly like the Where-Object cmdlet that you're used to. Most people just use it to filter collections on a filterscript (stay tuned) but it also takes other arguments.
  • {$_ % 2}
    • This is the filterscript, or basically the criteria we're using to split up our collection. It will effectively create a true and a false list like the condition in an if statement. The percent sign is the modulus operator and will determine if the number is divisible by two without a remainder or not.
  • 'split'
    • This is the mode. By default, the collection is filtered using the filterscript like when using Where-Object and only the objects matching the condition are returned. But that's not the only mode! We're going to use the split mode to break it into two collections. Maybe another blog post will come out on some of the other modes.

That’s it!

Written on June 20, 2018