Powershell 识别列表中存在多次的所有项目,并将其全部列出

Powershell 识别列表中存在多次的所有项目,并将其全部列出,powershell,Powershell,我有一个列表,其中重复了几个项目。我需要确定这些项目,并创建一个新列表,以包括所有重复的项目,但每次它们再次出现 清单如下: apple orange pear carrot tomato cucumber apple apple apple cucumber tomato 这是苹果x4,番茄x2,黄瓜x2和其余的x1 所需的新名单将是: apple apple apple apple tomato tomato cucumber cucumber 这将忽略仅存在一次的,并在每次出现时列出多

我有一个列表,其中重复了几个项目。我需要确定这些项目,并创建一个新列表,以包括所有重复的项目,但每次它们再次出现

清单如下:

apple
orange
pear
carrot
tomato
cucumber
apple
apple
apple
cucumber
tomato
这是苹果x4,番茄x2,黄瓜x2和其余的x1

所需的新名单将是:

apple
apple
apple
apple
tomato
tomato
cucumber
cucumber
这将忽略仅存在一次的,并在每次出现时列出多次存在的

我试过:

$Fruits = Get-Content -Path C:\temp\Fruits.txt

$Unique = $Fruits | Select-Object -Unique
$MoreThanOne = Compare-Object –referenceobject $Unique –differenceobject $Fruits | Select-Object -ExpandProperty inputobject

$MoreThanOne
这将产生:

apple
apple
apple
cucumber
tomato
每种水果少了一个


有什么想法吗?

通过比较两个对象并保存差异,您基本上可以执行
($Unique-“每个条目一次”)
。这是因为您需要保存所有条目的变量与保存每个条目一次的变量之间的差异

更好的解决方案是提供
组对象
。这将所有条目分组在一起,以便您可以查找包含多个条目的条目

命令
Get Content-Path C:\temp\Fruits.txt | Group Object
输出以下内容:

Count Name                      Group
----- ----                      -----
    4 apple                     {apple, apple, apple, apple}
    2 tomato                    {tomato, tomato}
    2 cucumber                  {cucumber, cucumber}
    1 carrot                    {carrot}
    1 pear                      {pear}
    1 orange                    {orange}
如果您现在筛选正确:

Get-Content -Path C:\temp\Fruits.txt | Group-Object | Where-Object {$_.Count -gt 1} | Select-Object -ExpandProperty Group
输出如下:

apple
apple
apple
apple
tomato
tomato
cucumber
cucumber

谢谢$水果|组|?计数-gt 1 |%组工作!