Powershell convierte la matriz de objetos en PSCustomObject
Sep 09 2020
Me gustaría convertir esta matriz de objetos.
Name CIDR
---- ----
sdc-MO 10.92.18.136/20
sdc-RM 10.77.6.34/20
en un solo [PSCustomObject]
sdc-MO sdc-RM
------- -------
{10.92.18.136/20} {10.77.6.34/20}
Por favor sugiera alguna forma fácil. Gracias
Respuestas
1 MathiasR.Jessen Sep 09 2020 at 18:27
Agregue cada objeto a una tabla hash u otro tipo de diccionario de diccionario, luego use el diccionario para crear el objeto (cada entrada se convertirá en una propiedad separada):
$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 será como lo que describiste en la pregunta:
PS C:\> $newObject
sdc-MO sdc-RM
------ ------
{10.92.18.136/20} {10.77.6.34/20}