0

I have an array of hashtables and I am trying to filter it to those who has a property value to true, but this what I am doing does not looks good.

# object looks like this
$array = @(
    @{ Name = 'First'; Passed = $true }
    @{ Name = 'Second'; Passed = $false }
)

function Filter {
    Param($array)
    $filtered = @()

    foreach ($item in $array) {
        if ($item.Passed = $true) {
            $filtered += $item
        }
    }

    return $filtered
}

Is there any other way I can get all elements who has property Passed = $True without the need to add those to another array.

3
  • 1
    $newarray = @($array | Where-Object { $_.Passed }) Commented Oct 9, 2019 at 14:05
  • @AnsgarWiechers won't that catch anything with a Passed that is "truthy"? (i.e. not just the ones with a value of $true) Commented Oct 9, 2019 at 14:11
  • 1
    @MikeShepard Yes. But since the key seems to have only boolean values that shouldn't be an issue. Otherwise change the condition to $_.Passed -eq $true. Commented Oct 9, 2019 at 14:21

1 Answer 1

1

Just pipe your array into a Where-Object like so:

$array = @(
    @{ Name = 'First'; Passed = $True }
    @{ Name = 'First'; Passed = $False }
)

$array = $array | Where-Object Passed -EQ $True
Sign up to request clarification or add additional context in comments.

2 Comments

Beware that this will not give an array result if the Where-Object filter returns less than 2 items.
Good point, changing it to $array = @($array | Where-Object Passed -EQ $True) would fix that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.