32

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
craig
  • 25,664
  • 27
  • 119
  • 205

1 Answers1

53

Use:

$Items.Title -contains 'foo'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eris
  • 7,378
  • 1
  • 30
  • 45
  • Is there any way to check $items Property like if Title exists or not ? – Dhirendra Patil Nov 18 '20 at 06:26
  • 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 https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject?view=powershell-7.2 – LosManos Jul 14 '22 at 08:08