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

PowerShell创建PSObject后添加子对象重复问题解决

解决PowerShell构建客户-域名对象树的重复问题

问题场景

需要读取未排序的客户-域名CSV文件,构建层级对象树。CSV格式如下:

Kunde,Domain
"Customer1", "DomainName1"
"Customer2", "DomainName3"
"Customer1", "DomainName2"
"Customer3", "DomainName4"

预期结构

Customer1--- some attributes
   |__ Domainname1---some attributes
   |__ Domainname2---some attributes
Customer2--- some Attribute 
   |__ Domainname3---some attributes
Customer3--- some attributes
   |__ Domainname1---some attributes
   |__ Domainname2---some attributes
   |__ Domainname3---some attributes

实际错误输出

Customer1--- some attributes
   |__ Domainname1---some attributes
   |__ Domainname2---some attributes
   |__ Domainname3---some attributes
Customer2--- some Attribute 
   |__ Domainname1---some attributes
   |__ Domainname2---some attributes
   |__ Domainname3---some attributes

问题根源

原代码中所有客户共用同一个$Customer_Properties对象实例,所有域名共用同一个$Customer_Domain_Properties实例。PowerShell中对象是引用类型,修改共享实例会导致所有关联对象的属性同步变化,这就是为什么添加到Customer2的域名会出现在Customer1下。

修正代码

Function ReadCustomerDomains([string]$File )
{
    $CSVData = Import-Csv $File -Delimiter ","
    $CustomerListObject = New-Object PSObject 

    # 初始化客户对象
    ForEach ($Item in $CSVData)   
    {
        $customerName = $Item.Kunde.Trim()
        if (-not (Get-Member -InputObject $CustomerListObject -Name $customerName))
        {
            # 为每个客户创建独立的属性对象
            $customerProps = [PSCustomObject]@{
                # 在这里定义客户的属性,例如:
                # Status = "Active"
                # CreationDate = Get-Date
            }
            $CustomerListObject | Add-Member -NotePropertyName $customerName -NotePropertyValue $customerProps
        }
    }

    # 为客户添加域名
    ForEach ($Item in $CSVData)   
    {
        $customerName = $Item.Kunde.Trim()
        $domainName = $Item.Domain.Trim()
        
        $CustomerItem = $CustomerListObject.$customerName
        # 检查域名是否已存在,避免重复添加
        if (-not (Get-Member -InputObject $CustomerItem -Name $domainName))
        {
            # 为每个域名创建独立的属性对象
            $domainProps = [PSCustomObject]@{
                # 在这里定义域名的属性,例如:
                # ExpiryDate = (Get-Date).AddYears(1)
                # Registrar = "Example"
            }
            Add-Member -InputObject $CustomerItem -NotePropertyName $domainName -NotePropertyValue $domainProps
        }
    }

    return $CustomerListObject
}

核心修改说明

  • 避免对象复用:每次创建客户或域名属性时,都新建一个[PSCustomObject]实例,确保每个客户/域名拥有独立的属性对象
  • 清理空格:对CSV中的客户名和域名做Trim()处理,避免因空格导致的匹配错误
  • 重复检查:添加域名前先检查是否已存在,防止CSV重复条目导致重复添加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:55:04