powershell 创建后将子对象添加到PSObject

wbgh16ku  于 2023-04-30  发布在  Shell
关注(0)|答案(1)|浏览(135)

当使用PowerShell时,Add-Member函数可以用于对象树的操作。
以下函数应读取包含客户及其相应域名的CSV,并构建对象树,如下所示:

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

CSV文件是一个未排序的客户及其域列表,其外观如下:

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

在将domainname 3添加到customer 2之后,domainname 3在customer 1对象上也被视为可能的子对象。
结果树在调试器中看起来像这样:

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

我怎样才能得到计划的结果?
powershell函数:

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

    ForEach ($Item in $CSVData)   
    {
        if ( Get-Member -InputObject $CustomerListObject -name $($Item.Kunde) )
        {
        }
        else
        {
            $CustomerListObject | Add-Member -NotePropertyName "$($Item.Kunde)" -NotePropertyValue $Customer_Properties
        }
    }

    ForEach ($Item in $CSVData)   
    {
        $CustomerItem = $CustomerListObject.$($Item.Kunde)
        Add-Member -InputObject $CustomerItem -NotepropertyName "$($Item.Domain)"  -NotePropertyValue $Customer_Domain_Properties
        $CustomerItem =$Null 
    }
    $CustomerList += $CustomerListObject
    return  $CustomerList
}
2ledvvac

2ledvvac1#

尝试以下操作:

$filename = "c:\temp\test.csv"
$headers = 'Customer', 'Domain'
$csv = Import-Csv -Path $filename -Header $headers
$customers = $csv | Group-Object -Property 'Customer'

$table = [System.Collections.ArrayList]::new()
foreach($customer in $customers)
{
   $newRow = New-Object -TypeName psobject
   $newRow | Add-Member -NotePropertyName Customer -NotePropertyValue $customer.Name

   $domainObj = New-Object -TypeName PSObject
   foreach($domain in $customer.Group)
   {
      $attributes = [System.Collections.Generic.Dictionary[string,object]]::new()
      for($i = 0; $i -lt 4; $i++)
      {
         $attributes.Add('Attribute' + $i, $i)
      }
      $domainObj | Add-Member -NotePropertyName $domain.Domain -NotePropertyValue $attributes
   }
   $newRow | Add-Member -NotePropertyName Domains -NotePropertyValue $domainObj
   $table.Add($newRow) | Out-Null
}
$table | foreach { $_.Customer; $_.Domains | foreach {$_ | Format-List} }

相关问题