Determine if an array of PSCustomObject's contains an instance with a property value
Asked Answered
B

1

37

I need to determine if an array of PSCustomObjects contains an item with its Title property matching a value. I need a Boolean value for use with Pester assertions:

$Items -<function> $Name | Should Be $True

Assuming:

$Items = @()
$Items += [PsCustomObject]@{Title='foo';Url='http://f.io'}
$Items += [PsCustomObject]@{Title='bar';Url='http://b.io'}

Contains does not work:

PS> $Items -contains 'foo'
False

Match returns the matching instance, but it is not a Boolean:

PS> $Items -match 'foo'

Title  Url
-----  ---
foo    http://f.io

I suppose I could:

($Items -Match $Name).Count | Should Be 1

Is there a better option?

Bass answered 19/6, 2015 at 13:37 Comment(1)
@Bass for match: [bool]($Items -match 'foo')Pulliam
R
61

Use:

$Items.Title -contains 'foo'
Resonant answered 8/8, 2015 at 17:49 Comment(2)
Is there any way to check $items Property like if Title exists or not ?Functionary
To check if the property exists; the way I have found is to enumerate them. $getResult | Get-Member -MemberType NoteProperty | Select -ExpandProperty Name and look for the result `($Items| Get-Member -MemberType NoteProperty | Select -ExpandProperty Name) -contains 'Title' as seen in learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/…Naquin

© 2022 - 2024 — McMap. All rights reserved.