Powershell convert Array of Objects into PSCustomObject

Viewed 2740

I would like to convert this array of objects

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

into a single [PSCustomObject]

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

Please suggest any easy way.. Thanks

1 Answers

Add each object to a hashtable or other dictionary dictionary type, then use the dictionary to create the object (each entry will become a separate property):

$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 will be like what you described in the question:

PS C:\> $newObject

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