7

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.

2
  • I'm not understanding the "to this output" part because a parameter is still input. But the = in -param = @{ ... } is invalid. Otherwise, you want your script to create a hashtable of hashtables? With what keys? Or you want the hashtables to be combined before the script even receives them? Commented Feb 18, 2020 at 18:56
  • @BACON oops sorry, did some typo. Commented Feb 18, 2020 at 19:01

1 Answer 1

9

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
)
Sign up to request clarification or add additional context in comments.

3 Comments

Adding on to this, if you want to retain the order, you can declare the parameter as [ordered[]] which makes an ordered dictionary object and which functions similarly to a [hashtable], but retains the order you entered your data.
Sorry, to array variable but I tried this not sure why the output is just Hashtables: @( )
@TenUy inside the script, $Hashtables is already an array variable! You can replace my code with whatever you need. Try $hashtables[0] for example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.