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

PowerShell无匹配属性值时Join-Object使用问题求助

问题解决:Join-Object跨机器报错及对象合并方案

问题原因:Join-Object版本差异

那台正常运行的机器安装的是旧版本Join-Object模块,该版本在未指定LeftJoinProperties和RightJoinProperties时,默认对单条对象执行笛卡尔积合并(刚好符合你单条对象合并成一行的需求);而其他机器的新版本Join-Object模块强制要求明确指定连接属性,避免意外生成大量笛卡尔积结果,因此会报错。

最优解决方案:直接合并属性(无需依赖Join-Object版本)

由于你每次循环中$ip和$compdock都是对应同一台电脑的单条记录,不需要基于属性关联匹配,直接创建新的自定义对象合并两者属性即可,完全避开Join-Object的版本问题,代码更简洁稳定:

修改后的完整脚本

$Computers = Get-ADComputer -Filter * -SearchBase $OUPath | Select-Object -ExpandProperty Name

Foreach ($Computer in $Computers){
    $ip = Test-Connection -ComputerName $Computer -Count 1 -ErrorAction SilentlyContinue | Select-Object IPV4Address
    $compdock = Get-WmiObject -Namespace root\dell\sysinv -Class dell_softwareidentity -ComputerName $Computer -ErrorAction SilentlyContinue | 
                Where-Object {$_.ElementName -like "WD19*"} | 
                Select-Object PSComputerName, serialnumber

    # 处理机器离线情况
    if ($null -eq $ip){
        $ip = [PSCustomObject]@{ IPV4Address = "Computer Not On" }
        $compdock = [PSCustomObject]@{ 
            PSComputerName = $Computer
            serialnumber = ""
        }
    # 处理未找到扩展坞情况
    } elseif ($null -eq $compdock){
        $compdock = [PSCustomObject]@{ 
            PSComputerName = $Computer
            serialnumber = "No Dock Found"
        }
    }

    # 直接合并两个对象的属性为新对象
    $data = [PSCustomObject]@{
        IPV4Address = $ip.IPV4Address
        PSComputerName = $compdock.PSComputerName
        SerialNumber = $compdock.serialnumber
    }

    $data | Export-Csv -Path $Path -Append -NoTypeInformation
}

若坚持使用Join-Object的兼容写法

如果你一定要保留Join-Object调用,可通过给两个对象添加临时匹配属性,让新版本模块能找到关联键:

# 在合并前给两个对象添加相同的临时键
$ip | Add-Member -MemberType NoteProperty -Name TempKey -Value 1
$compdock | Add-Member -MemberType NoteProperty -Name TempKey -Value 1

# 指定临时键作为连接属性
$data = Join-Object -Left $ip -Right $compdock -LeftJoinProperties TempKey -RightJoinProperties TempKey

# 移除临时键(可选,避免导出到CSV)
$data | Select-Object -Property * -ExcludeProperty TempKey

这种写法能兼容新旧版本的Join-Object模块,但不如直接创建自定义对象高效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:30:22