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
相关产品推荐
相关产品推荐

