You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PowerShell中提取多数据集的共同标识ID(字段名不同)

高效提取三个PowerShell数据集的共有标识值

给定三个通过API获取的PowerShell数据集:

$data1 = @(
    [PSCustomObject]@{ Id='1'; Service='Service1'; Propertyx=1; Price='5' }
    [PSCustomObject]@{ Id='2'; Service='Service1'; Propertyx=1; Price='17' }
    [PSCustomObject]@{ Id='3'; Service='Service1'; Propertyx=1; Price='3' }
    [PSCustomObject]@{ Id='4'; Service='Service1'; Propertyx=1; Price='7' }
)

$data2 = @(
    [PSCustomObject]@{ AlsoId='1'; Service='Service1'; Propertyx=1; Price='5' }
    [PSCustomObject]@{ AlsoId='2'; Service='Service1'; Propertyx=1; Price='17' }
    [PSCustomObject]@{ AlsoId='5'; Service='Service1'; Propertyx=1; Price='3' }
    [PSCustomObject]@{ AlsoId='6'; Service='Service1'; Propertyx=1; Price='7' }
)

$data3 = @(
    [PSCustomObject]@{ IdToo='1'; Service='Service1'; Propertyx=1; Price='5' }
    [PSCustomObject]@{ IdToo='2'; Service='Service1'; Propertyx=1; Price='17' }
    [PSCustomObject]@{ IdToo='5'; Service='Service1'; Propertyx=1; Price='3' }
    [PSCustomObject]@{ IdToo='7'; Service='Service1'; Propertyx=1; Price='7' }
)

三个数据集的标识字段分别为Id、AlsoId、IdToo,需找出三者共有的标识值(示例结果为1和2),并生成仅包含这些标识对应项的新对象。以下是高效实现方法:


方法1:Linq集合交集(适用于大数据集)

利用.NET的LinqIntersect方法快速计算集合交集,性能比纯PowerShell语法更优,适合处理大规模数据:

# 提取各数据集的标识值数组
$ids1 = $data1.Id
$ids2 = $data2.AlsoId
$ids3 = $data3.IdToo

# 逐步计算三者的共有标识
$commonIds = [System.Linq.Enumerable]::Intersect([string[]]$ids1, [string[]]$ids2)
$commonIds = [System.Linq.Enumerable]::Intersect($commonIds, [string[]]$ids3)

# 根据共有标识过滤原数据集(这里以保留$data1的结构为例,可按需替换其他数据集)
$filteredResult = $data1 | Where-Object { $_.Id -in $commonIds }

# 输出结果
$filteredResult

方法2:纯PowerShell原生语法(适用于小数据集)

如果数据量不大,直接用Where-Object结合-contains判断,语法更直观:

# 提取各数据集的标识值集合
$ids1 = $data1.Id
$ids2 = $data2.AlsoId
$ids3 = $data3.IdToo

# 过滤出同时存在于三个集合的标识对应的项
$filteredResult = $data1 | Where-Object { $ids2 -contains $_.Id -and $ids3 -contains $_.Id }

# 输出结果
$filteredResult

扩展:合并多数据集属性

如果需要将三个数据集的对应属性合并到同一个对象中,可遍历共有标识并组合:

$combinedResult = foreach ($id in $commonIds) {
    $item1 = $data1 | Where-Object Id -eq $id
    $item2 = $data2 | Where-Object AlsoId -eq $id
    $item3 = $data3 | Where-Object IdToo -eq $id

    [PSCustomObject]@{
        Id = $id
        Service = $item1.Service
        Propertyx = $item1.Propertyx
        Price_FromData1 = $item1.Price
        Price_FromData2 = $item2.Price
        Price_FromData3 = $item3.Price
    }
}

# 输出合并后的对象
$combinedResult

内容的提问来源于stack exchange,提问作者Bohn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 02:20:20