Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Multidimensional Hash Table Array in Powershell

I was wondering if there was a shorter way to create a multidimentional hashtable array in powershell. I have been able to successfully create them with a couple of lines like so.

$arr = @{}
$arr["David"] = @{}
$arr["David"]["TSHIRTS"] = @{}
$arr["David"]["TSHIRTS"]["SIZE"] = "M"

That said I was wondering if there was any way to shorten this to something like this...

$new_arr["Level1"]["Level2"]["Level3"] = "Test" 

Where it would create a new level if it doesn't already exist. Thanks!

like image 971
John Smith Avatar asked Aug 17 '17 19:08

John Smith


People also ask

Is it possible to create multidimensional arrays in PowerShell?

Working with arrays is a fairly straightforward process, but what a lot of people don't realize is that PowerShell does not limit you to using basic, run-of-the-mill arrays. You can also create multi-dimensional arrays.

What is GetEnumerator in PowerShell?

GetEnumerator. A hash table is a single PowerShell object, to sort, filter or work with the pipeline you can unwrap this object into it's individual elements with the GetEnumerator() method.

How do I create an empty Hashtable in PowerShell?

An empty PowerShell hash table is created using @{}. PowerShell hash table values are added using $table. Add(key, value) syntax or $table. key = value syntax.


1 Answers

You need to name/define the sub-levels or else the interpreter doesn't know what kind of type it's working with (array, single node, object, etc.)

$arr = @{
    David = @{
        TSHIRTS = @{
            SIZE = 'M'
        }
    }
}
like image 192
Maximilian Burszley Avatar answered Sep 20 '22 17:09

Maximilian Burszley