Snippet: Filtering Arrays

A recent tweet inspired me to tell you about an easy way to filter your arrays in PowerShell - It even looks somewhat similar to Pythons well known and loved list comprehensions

To keep it short and simple, instead of:

$fruits = @("apple", "banana", "cherry", "kiwi", "mango")
$fruitsWithA = [System.Collections.ArrayList]@()

foreach ($fruit in $fruits) {
    if ($fruit -like "*a*") {
        $fruitsWithA.Add($fruit)
    }
}

$fruitsWithA
# apple
# banana
# mango

Do it like this:


$fruits = @("apple", "banana", "cherry", "kiwi", "mango")

$fruitsWithA = $fruits | Where-Object { $_ -like "*a*" }

$fruitsWithA
# apple
# banana
# mango