如何在两个数组之间找到差值并从第三个数组返回值?

时间:2017-05-10 11:59:44

标签: powershell

我想比较两个数组并使用差分值从另一个数组返回另一个值。

通过这段代码,我能够确定" b"来自$ array1的$ array2中不包含。但是,我不知道如何链接" b"到$ array3中的2并返回该值。

$array1 = (@("a","b","c"))
$array2 = (@("a","c"))
$array3 = (@(1,2,3))  # 1 should be linked to "a", 2 to "b" and 3 to "c"

$array1 | ForEach-Object {If ($_ -notin $array2) {$_}}

感谢您的帮助。

感谢。

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

$index = 0..($array1.Count-1) | Where-Object { $array1[$_] -notin $array2 }
if ($index) { $array3[$index] }

答案 1 :(得分:1)

您可以使用compare-object

$array1 = @("a","b","c")
$array2 = @("a","c")
$array3 = @(1,2,3)  # 1 should be linked to "a", 2 to "b" and 3 to "c"

$diff = Compare-Object -ReferenceObject $array1 -DifferenceObject $array2  -PassThru

$diff | ForEach-Object { if($array1.Contains($_)){
       write-host $array3[$array1.IndexOf($_)]
   }
}