我们可以使用自定义函数来检查数组中是否已存在所需的数据对象。如果已经存在,则不需要再将其添加到数组中。下面是一个简单的示例代码:
function Add-UniqueObject{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[Object[]]$InputObject,
[Parameter(Mandatory=$true)]
[Object[]]$Array
)
foreach($item in $InputObject){
if($Array -notcontains $item){
$Array += $item
}
}
return $Array
}
# 使用示例
$myArray = @()
$myArray = Add-UniqueObject -InputObject ([PSCustomObject]@{Name="John"; Age=25}) -Array $myArray
$myArray = Add-UniqueObject -InputObject ([PSCustomObject]@{Name="Patrick"; Age=32}) -Array $myArray
$myArray = Add-UniqueObject -InputObject ([PSCustomObject]@{Name="John"; Age=25}) -Array $myArray
在上面的示例中,我们首先定义了一个名为Add-UniqueObject的函数,该函数接受两个参数:InputObject和Array。InputObject包含我们想要添加到数组的PSCustomObject,而Array是我们要检查并添加到的目标数组。
在函数中,我们使用foreach循环来遍历InputObject中的每个项。在循环中,我们使用-notcontains运算符来检查当前项是否已经存在于数组中。如果不存在,则使用 += 运算符将当前项添加到数组中。
最后,我们可以使用Add-UniqueObject函数来添加PSCustomObject到数组中,因为函数会检查是否已经存在该对象。在以上示例代码中,我们先将一个名为John的人员对象和一个名为Patrick的人员对象添加到数组中,然后再添加另一个名为John的人员对象。由于John的人员对象已经存在于
下一篇:避免重复条目的数据库结构