问题描述
我有一个具有以下结构的对象数组:
I have an array of objects of the following structure:
structure Disk
{
int UID;
String Computer;
}
一台计算机可能有一堆共享磁盘,一个磁盘可能在计算机之间共享.
A computer may have a bunch of shared disks, and a disk may be shared among computers.
我想找出所有计算机共有的所有磁盘.例如,我有计算机 A、B 和 C;磁盘 1、2 和 3.磁盘阵列为{1,A}、{1,B}、{2,A}、{2,B}、{2,C}、{3,A}.我想要的结果应该是磁盘2,因为它出现在A、B和C上.
I want to find out all the disks common to all the computers. For example, I have computer A, B, and C; Disks 1, 2, and 3.The disk array is {1,A}, {1,B}, {2,A},{2,B},{2,C},{3,A}.The result that I want should be the disk 2, because it appears on A, B, and C.
有没有有效的方法来实现这一目标?
Is there a effective way to achieve this?
使用多个 foreach 循环是可以实现的,但我绝对想要一个更好的方法.我正在考虑像交集这样的操作,但在 PowerShell 中没有找到.
With multiple foreach loops it's achievable, but definitely I want a better way. I'm thinking about operations like intersection, but didn't find this in PowerShell.
推荐答案
假设 $arr
是数组,你可以这样做:
Assuming $arr
is the array, you can do like this:
$computers = $arr | select -expand computer -unique
$arr | group uid | ?{$_.count -eq $computers.count} | select name
一般来说,我会像这样在 Powershell 中处理联合和交集:
In general, I would approach union and intersection in Powershell like this:
$a = (1,2,3,4)
$b = (1,3,4,5)
$a + $b | select -uniq #union
$a | ?{$b -contains $_} #intersection
但是对于您所问的问题,上述解决方案运行良好,并且与术语标准定义中的并集和交集无关.
But for what you are asking, the above solution works well and not really about union and intersection in the standard definition of the terms.
更新:
我已经编写了 pslinq,它提供了 Union-List
和 Intersect-List代码>,有助于实现与 Powershell 的集合并集和交集.
I have written pslinq which provides Union-List
and Intersect-List
that help to achieve set union and intersection with Powershell.
这篇关于PowerShell中的并集和交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!