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!

1
  • 1
    You're after autovivification and no, PowerShell doesn't have it. Commented Aug 17, 2017 at 19:34

2 Answers 2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.