Union and Intersection in PowerShell?

后端 未结 4 870
猫巷女王i
猫巷女王i 2020-12-13 08:25

I have an array of objects of the following structure:

structure Disk
{
  int UID;
  String Computer;
}

A computer may have a bunch of shar

相关标签:
4条回答
  • 2020-12-13 09:08

    You can also do

    $a = (1,2,3,4)
    $b = (1,3,4,5)
    Compare-Object $a $b -PassThru -IncludeEqual                   # union
    Compare-Object $a $b -PassThru -IncludeEqual -ExcludeDifferent # intersection
    

    Doesn't work if $a is null though.

    0 讨论(0)
  • 2020-12-13 09:11

    While this won't work in the earliest versions, in more recent versions you can just call the .NET LINQ extension functions directly, e.g.

    [system.linq.enumerable]::union([object[]](1,2,3),[object[]](2,3,4))
    

    (Without the cast to some enumerable type, PowerShell throws a "cannot find overload" error.)

    This definitely works in PowerShell V4 and V5 and definitely doesn't in V2. I don't have a system at hand with V3.

    0 讨论(0)
  • 2020-12-13 09:15

    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
    

    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.

    Update:

    I have written pslinq which provides Union-List and Intersect-List that help to achieve set union and intersection with Powershell.

    0 讨论(0)
  • 2020-12-13 09:17

    For set subtraction (a - b):

    $a | ?{-not ($b -contains $_)}

    0 讨论(0)
提交回复
热议问题