[Array] How to append to an entry name?

Hi all,

Let me specify what I’m struggling with here:

I have a dynamic array where I don’t know what entries or values will be added in forehand. The array then has to be converted to Json

Here is my problem:

When two values share the same entry name, how do you append to that entry?

 

My code:

$Body = New-Object System.Collections.ArrayList

If ($PSBoundParameter.ContainsKey('NTPEnabled')) {

    [void]$Body.Add(

        @{

            NTP = @{

                ProtocolEnabled = $NTPEnabled

            }

        }

    )

}

If ($PSBoundParameter.ContainsKey('NTPServers')) {

    [void]$Body.Add(

        @{

             NTP = @{

                NTPServers = @(

                    $NTPServers | ForEach-Object {

                        $_

                    }

                )

            }

        }

    )

}

If both is used, PowerShell outputs the following:

Name	Value
—-	—–
NTP	NTPServers=x.x.x.x,y.y.y.y
NTP	ProtocolEnabled=true

The values both share the same entry, but they are indivual entries inside NTP.

I read somewhere about nested arrays, but im not sure.

 

Any help is appreciated.

Thanks in advance!

Please read the pinned posting at the top of the forum and highlight your code and output with the PRE. Assuming you are putting this together for a JSON body, {} are hashtable and [] are arrays, so the code should look soemthing like this:

$NTPEnabled = $True
$NTPServers = '1.1.1.1','2.2.2.2'

$ntp = @{}
$ntpProps = @{}

#If ($PSBoundParameter.ContainsKey('NTPEnabled')) {
    $ntpProps.Add('ProtocolEnabled', $NTPEnabled)
#}

#If ($PSBoundParameter.ContainsKey('NTPServers')) {
    $ntpProps.Add('NTPServers', $NTPServers)
#}

$ntp.Add('NTP',$ntpProps)

$ntp | ConvertTo-Json

Output:

{
    "NTP":  {
                "ProtocolEnabled":  true,
                "NTPServers":  [
                                   "1.1.1.1",
                                   "2.2.2.2"
                               ]
            }
}

In the function for something like ProtocolEnabled, I would set a default value and remove the PSBoundParameters IF to always create a NTP part of the body, otherwise you will need to wrap the $ntp.Add with an IF statement to see if there were any passed values for Protocol or NTPServers.