Powershell: Creating and Using Nested Hash Tables

I was working on a new provisioning script for my work for creating new users, creating their home drives, and blah blah blah (that’s the technical term). During this while adding error detection and resolution, in dawned on me that one of the things I would like to do is get an email that contained the users that had issues or failed, and also I would like the email to contain each error for each user — but how was I going to do it?

Batman pensively rubbing his chin

Wait — I got it! Hash tables! Arrays! Something to that effect!

So I began my journey into figuring out how I was going to accomplish this.

The first place to start is the PowerShell help file (aka, “help about_hash_tables -full”). That certainly got me going with figuring out the details about it, but I also needed to read up the help files on arrays, because I began to slowly figure out that you can’t really — or at least it appears this way to me — nest hash tables within hash tables (I welcome being wrong about this). However, arrays can be nested within arrays. So to the help file on arrays I went (“help about_arrays -full”).

Again, not quite enough info for me, so the following articles REALLY helped enlighten me:

However, what I wasn’t really understanding was how to nest the arrays and hash tables two or more orders below. Maybe I just didn’t read the material well, or maybe I just had to get to work doing it.

So after some time and further reading, I figured it out. The gist of it is that you initialize an array, then in your loop initialize another array for a loop, then create a hash table that has the properties and values of the properties, create a PS object that has their properties defined as the hash table, then do the same process for the parent loop, and voila!

Ok, it’s not so voila, and that was a mouthful, so below is script I put together to explain it, with comments!

I don’t profess to be the expert on this, but it’s PowerShell, so there’s many paths to same destination — at least that’s what Don Jones says. :-p

Cheers!

Leave a Reply

Your email address will not be published. Required fields are marked *