Create a Multidimensional Hash Table Array in Powershell
Asked Answered
U

2

8

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!

Unwell answered 17/8, 2017 at 19:28 Comment(1)
You're after autovivification and no, PowerShell doesn't have it.Alaniz
G
11

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'
        }
    }
}
Goldthread answered 17/8, 2017 at 19:55 Comment(0)
V
2

Adding to @Maximilian's answer here is a more complete example how to use a multidimensional hashtable:

$acls = @{
Ordner1 = @{
    lesen     = 'torsten', 'timo';
    schreiben = 'Matthias', 'Hubert'
};
Ordner2 = @{
    schreiben = 'Frank', 'Manfred'; 
    lesen = 'Tim', 'Tom' }

}

Add data:

$acls.Ordner3=@{}
$acls.Ordner3.lesen='read'
$acls.Ordner3.schreiben='write','full'

Access:

$acls.Ordner2.schreiben

Result:

Frank

Manfred

Valentia answered 4/6, 2020 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.