powershell - 在powershell中,如何在一个数组中测试已经包含一个具有所有相同属性的对象?
问题描述
我想避免将重复项插入到 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
这种情况下)。这可以简单地使用 来完成Compare-Object
,默认情况下将输出任一对象的差异。的SideIndicator
值=>
表示不同之处在于传入-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)
}
推荐阅读
- celery - 芹菜服务很长时间后任务执行缓慢,但芹菜重启后仍然可以快速工作
- apache-spark - 无法使用 Spark 3.0.1 更改 Pyspark 中的分区数
- json - 如何使用 Visual Basic 6 将字节数组作为 json 发送?
- flutter - 如何自定义一个颤振包?
- firebase - Unity 访问 Firebase 数据库导致编辑器崩溃
- arrays - 在swift中使用其他文件中的函数填充数组
- facebook - 联系在 Facebook 上喜欢我的应用的人
- python-3.x - 如何使用 bsoup 在 xml 中查找字符串偏移量?
- sql-server - 无法使用 Python 连接 SQL Server
- laravel - S3 存储桶不允许在 laravel 中上传文件