Select 多个属性,其中一个属性在管道中必须是唯一的

Select multiple properties where one of the properties must be unique in a pipeline

使用 Select-Object,您可以使用 -Unique select 对象多次出现中的第一个。你也可以select只保留一些属性。但是,如果我只想检查一个 属性 的唯一性,过滤掉所有不唯一的而不是只留下其中一个,并允许其他属性不变地通过怎么办?具体来说,我有一个 PSCustomObject 列表,其中一个 属性 是基本名称,另一个是自动生成的缩写名称。我想过滤掉短名称多次出现的元素,但所有项目的基本名称都不同。 Select-Object 似乎不适合这项任务,但什么是?

编辑:澄清 - 这应该是结果:

> $A = [PSCustomObject]@{A = 1; B = 2}, [PSCustomObject]@{A = 2; B = 2}, [PSCustomObject]@{A = 4; B = 1}
> $A

A B
- -
1 2
2 2
4 1

> $A | Mystery-Cmdlet "B"

A B
- -
4 1

我想你必须用代码解决它

$A = [PSCustomObject]@{A = 1; B = 2}, [PSCustomObject]@{A = 2; B = 2}, [PSCustomObject]@{A = 4; B = 1}

$A | Add-Member -NotePropertyName Count -NotePropertyValue init

for ($i=0; $i -lt $a.Length; $i++) {
$a[$i].Count = ($A.B | Where-Object {$_ -eq $a[$i].B}).Count
}

$a | Where-Object {$_.Count -eq 1}

I have a list of PSCustomObjects…
I want to check for the uniqueness of only one property, filter out all non-unique ones and not just leave one of them, and allow the other properties to pass through unchanged…

让我们根据 PowerShell cmdlet 重写上述要求:

$A = @'
A,B
1,2
2,2
4,1
5,4
'@ | ConvertFrom-Csv -Delimiter ','        # a list of PSCustomObjects

$A |
  Group-Object -Property B |               # check for the uniqueness,
    Where-Object Count -eq 1 |             # filter out all non-unique ones,
      Select-Object -ExpandProperty Group  # and pass through the rest unchanged

输出62219608.ps1

A B
- -
4 1
5 4