4

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
        }
    }
}
2
  • Show us your code :-) Commented Jul 10, 2017 at 15:18
  • Added the current code to the post, currently I only have it echoing the contents of the hash table and I'm stuck on how to format all of the data. Commented Jul 10, 2017 at 15:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

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.