【发布时间】:2020-01-04 11:21:45
【问题描述】:
有两个 $A 和 $B 数组。我需要得到第三个 $C 数组,它由第一个数组的所有元素组成,而第二个数组中没有这些元素。 IE。 $A = $B + $C。当然$B数组的长度加上$C数组的长度等于$A数组的长度。
$A = 'a', 'b', 'c', 'a', 'a'
$B = 'b', 'a', 'a'
# This is an array that is consisted of elements of the first array that are not in the second array.
$C = 'a', 'c'
下一个动作本身不起作用,所以它会删除所有匹配项:
# Not suitable
$A | Where-Object { $B -notcontains $_ }
---
c
此解决方案应该有效。但是,据我了解,在 Powershell 中没有从数组中删除元素的操作。也就是没有这样的操作:{ Remove $j element from $A array }
ForEach ($i in $B) {
ForEach ($j in $A) {
if ($i -eq $j) { { Remove $j value from $A array }; break }
}
}
显然在学习 Powershell 的过程中,我错过了一些东西。我会问你是否有任何删除数组元素的操作。我怎样才能得到我想要的 $C 数组?
【问题讨论】:
-
将管道分配给 $C 变量,它将保存该管道的输出。如果你想确保结果是一个数组,就这样创建它...
[array]$C = YourPipelineCode | GoesHere
标签: powershell