Powershell convertit un tableau d'objets en PSCustomObject
Sep 09 2020
Je voudrais convertir ce tableau d'objets
Name CIDR
---- ----
sdc-MO 10.92.18.136/20
sdc-RM 10.77.6.34/20
en un seul [PSCustomObject]
sdc-MO sdc-RM
------- -------
{10.92.18.136/20} {10.77.6.34/20}
Veuillez suggérer n'importe quel moyen simple. Merci
Réponses
1 MathiasR.Jessen Sep 09 2020 at 18:27
Ajoutez chaque objet à une table de hachage ou à un autre type de dictionnaire de dictionnaire, puis utilisez le dictionnaire pour créer l'objet (chaque entrée deviendra une propriété distincte):
$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 sera comme ce que vous avez décrit dans la question:
PS C:\> $newObject
sdc-MO sdc-RM
------ ------
{10.92.18.136/20} {10.77.6.34/20}