Powershell mengubah Array of Objects menjadi PSCustomObject

Sep 09 2020

Saya ingin mengonversi larik objek ini

Name    CIDR
----    ----
sdc-MO  10.92.18.136/20
sdc-RM  10.77.6.34/20

menjadi satu [PSCustomObject]

sdc-MO           sdc-RM
-------           -------
{10.92.18.136/20} {10.77.6.34/20}

Mohon saran cara yang mudah .. Terima kasih

Jawaban

1 MathiasR.Jessen Sep 09 2020 at 18:27

Tambahkan setiap objek ke hashtable atau jenis kamus kamus lainnya, lalu gunakan kamus untuk membuat objek (setiap entri akan menjadi properti terpisah):

$array = @( [pscustomobject]@{ Name = 'sdc-MO'; CIDR = '10.92.18.136/20' } [pscustomobject]@{ Name = 'sdc-RM'; CIDR = '10.77.6.34/20' } ) # Prepare a new dictionary to hold the properties $newProperties = [ordered]@{}

foreach($inputObject in $array){
  # If we don't already have a property with the given name, 
  # create a new entry in the dictionary
  if(-not $newProperties.Contains($inputObject.Name)){
    $newProperties.Add($inputObject.Name, @())
  }

  # Add the `CIDR` value to the corresponding property name
  $newProperties[$inputObject.Name] += $inputObject.CIDR } $newObject = [pscustomobject]$newProperties

$newObject akan seperti yang Anda jelaskan dalam pertanyaan:

PS C:\> $newObject

sdc-MO            sdc-RM
------            ------
{10.92.18.136/20} {10.77.6.34/20}