Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Array of Hashtable

Tags:

powershell

How do you pass some data from parameter to an Array of Hashtable?

filnemane.ps1 -param @{ a = 1, b = 2, c =3}, @{ a = 4, b = 5, c =6}

to this output:

$param = @(
           @{
             a=1,
             b=2,
             c=3
            },
           @{
             a=4,
             b=5,
             c=6
            }
          )

Thanks.

like image 660
Ten Uy Avatar asked Jan 26 '23 07:01

Ten Uy


1 Answers

You declare a parameter to be of type [hashtable[]] (that is, an array of [hashtable]'s):

# filename.ps1
param(
    [hashtable[]]$Hashtables
)

Write-Host "Hashtables: @("
foreach($hashtable in $Hashtables){
    Write-Host "  @{"
    foreach($entry in $hashtable.GetEnumerator()){
        Write-Host "    " $entry.Key = $entry.Value
    }
    Write-Host "  }"
}
Write-Host ")"

With you're sample input you'd get something like:

PS C:\> .\filename.ps1 -Hashtables @{ a = 1; b = 2; c =3},@{ a = 4; b = 5; c =6}
Hashtables: @(
  @{
     c = 3
     b = 2
     a = 1
  }
  @{
     c = 6
     b = 5
     a = 4
  }
)

Notice that the output won't necessarily retain the key order from the input, because, well, that's not how hash tables work :)


As Matthew helpfully points out, if maintaining the key order is important, go with an ordered dictionary instead ([ordered]@{}).

To support accepting either kind without messing up the key order, declare the parameter type as an array of [System.Collections.IDictionary] - an interface that both types implement:

param(
    [System.Collections.IDictionary[]]$Hashtables
)
like image 122
Mathias R. Jessen Avatar answered Feb 04 '23 16:02

Mathias R. Jessen