Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在powershell中,如何在已包含具有所有相同属性的对象的数组中进行测试?_Powershell_Pscustomobject - Fatal编程技术网

在powershell中,如何在已包含具有所有相同属性的对象的数组中进行测试?

在powershell中,如何在已包含具有所有相同属性的对象的数组中进行测试?,powershell,pscustomobject,Powershell,Pscustomobject,我希望避免在powershell中的数组中插入重复项。尝试使用-notcontains似乎无法与PSCUstomObject数组一起使用 这是一个代码示例 $x = [PSCustomObject]@{ foo = 111 bar = 222 } $y = [PSCustomObject]@{ foo = 111 bar = 222 } $collection = @() $collection += $x if ($collection -notcont

我希望避免在powershell中的数组中插入重复项。尝试使用
-notcontains
似乎无法与
PSCUstomObject
数组一起使用

这是一个代码示例

$x = [PSCustomObject]@{
    foo = 111
    bar = 222
}

$y = [PSCustomObject]@{
    foo = 111
    bar = 222
}

$collection = @()

$collection += $x

if ($collection -notcontains $y){
    $collection += $y
}


$collection.Count #Expecting to only get 1, getting 2
我会用这个

$x = [PSCustomObject]@{
    foo = 111
    bar = 222
}

$y = [PSCustomObject]@{
    foo = 111
    bar = 222
}
$collection = [System.Collections.Arraylist]@()

[void]$collection.Add($x)

if (Compare-Object -Ref $collection -Dif $y -Property foo,bar | Where SideIndicator -eq '=>') {
    [void]$collection.Add($y)
}
说明:

将一个自定义对象与另一个自定义对象进行比较并非易事。此解决方案比较您关心的特定属性(本例中为
foo
bar
)。只需使用
比较对象
,即可完成此操作,默认情况下,这将输出任一对象中的差异。
=>
侧指示灯
值表示差异在于传递到
-difference
参数的对象

[System.Collections.Arraylist]
类型用于数组,以避免在增长数组时通常出现的效率低下的
+=
。由于
.Add()
方法生成所修改索引的输出,因此使用
[void]
强制转换来抑制该输出


您可以动态地使用有关属性的解决方案。您可能不想将属性名称硬编码到
Compare Object
命令中。您可以执行如下操作

$x = [PSCustomObject]@{
    foo = 111
    bar = 222
}

$y = [PSCustomObject]@{
    foo = 111
    bar = 222
}
$collection = [System.Collections.Arraylist]@()

[void]$collection.Add($x)
$properties = $collection[0] | Get-Member -MemberType NoteProperty |
                  Select-Object -Expand Name

if (Compare-Object -Ref $collection -Dif $y -Property $properties | Where SideIndicator -eq '=>') {
    [void]$collection.Add($y)
}

这就是我要找的。感谢您提供了一个如何不硬编码属性名称的解决方案。答案与我的答案基本相同,只是您不关心结果,只关心是否有任何结果:(
@($collection).count
,您需要强制数组,否则您将在单例情况下计数字符)。