确定一个 PSCustomObject 数组中是否包含具有某个属性值的实例

35
我需要确定一个 PSCustomObject 数组中是否包含其 Title 属性匹配某个值的项。我需要一个布尔值,用于 Pester 断言使用:
$Items -<function> $Name | Should Be $True

假设:

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

Contains 不起作用:

PS> $Items -contains 'foo'
False

Match返回匹配实例,但它不是布尔值:

PS> $Items -match 'foo'

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

我想我可以:

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

有更好的选择吗?


3
对于匹配:[bool]($Items -match 'foo'),翻译为:判断变量$Items中是否包含'foo',返回布尔值。 - CB.
1个回答

57

使用:

$Items.Title -contains 'foo'

有没有办法检查 $items 属性,例如是否存在 Title? - Dhirendra Patil
检查属性是否存在的方法是枚举它们。 $getResult | Get-Member -MemberType NoteProperty | Select -ExpandProperty Name 并查找结果 `($Items| Get-Member -MemberType NoteProperty | Select -ExpandProperty Name) -contains 'Title',如 https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-pscustomobject?view=powershell-7.2 中所示。 - LosManos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接