Powershell converte array di oggetti in PSCustomObject
Sep 09 2020
Vorrei convertire questo array di oggetti
Name CIDR
---- ----
sdc-MO 10.92.18.136/20
sdc-RM 10.77.6.34/20
in un unico [PSCustomObject]
sdc-MO sdc-RM
------- -------
{10.92.18.136/20} {10.77.6.34/20}
Si prega di suggerire un modo semplice .. Grazie
Risposte
1 MathiasR.Jessen Sep 09 2020 at 18:27
Aggiungi ogni oggetto a una tabella hash o un altro tipo di dizionario di dizionario, quindi utilizza il dizionario per creare l'oggetto (ogni voce diventerà una proprietà separata):
$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 sarà come quello che hai descritto nella domanda:
PS C:\> $newObject
sdc-MO sdc-RM
------ ------
{10.92.18.136/20} {10.77.6.34/20}