Kuks35
Kuks35

Reputation: 43

Nested hashtable export in PowerShell?

I'm currently trying to create a easy to read document containing all devices on are network (3k+). Currently I have all my data within nested hashtables like so:

$devices = @{"hostname" = @{"Mac Address" = @{"IP Address" = "True or False"}}}

It stores the hostname of the device in $devices. Within the $hostname there is a hashtable containing all MAC addresses associated with that hostname. Within the MAC address there is a hashtable containing all IPs associated with that MAC address.

I've already created part of the script that creates the hashtable and stores the data. I have ran into a road block with exporting the data into a CSV that can be read in Excel with the format of.

Hostname, Mac Address, IP Address
server1, MM.MM.MM.SS.SS.SS , 1.1.1.1
                             1.1.1.2
         MM.MM.MN.SS.SS.SA , 1.1.1.3
server2, MM.MM.MB.SS.SS.ST , 1.2.3.1
                           , 1.5.2.1

and so on.

Edit:

foreach ($hostname in $devices.Keys) {
    echo $hostname
    foreach ($Macs in $devices.$hostname.Keys) {
        echo $Macs
        foreach ($IPs in $devices.$hostname.$Macs.Keys) {
            echo $IPs
        }
    }
}

Upvotes: 4

Views: 1685

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

Create custom objects in your innermost loop, collect the output in a variable, then export the data:

$csv = foreach ($hostname in $devices.Keys) {
    foreach ($MAC in $devices.$hostname.Keys) {
        foreach ($IP in $devices.$hostname.$Macs.Keys) {
            [PSCustomObject]@{
                'Hostname'    = $hostname
                'MAC Address' = $MAC
                'IP Address'  = $IP
            }
        }
    }
}

$csv | Export-Csv 'C:\path\to\output.csv' -NoType

If you want output exactly like your example (which I wouldn't recommend) you need to keep track of the previous $hostname and $MAC and create blank object properties in case those match the respective current value.

Upvotes: 2

Related Questions