Nested hash table export in PowerShell?
I am currently trying to create an easy-to-read document containing all devices on the network (3k +). Currently I have all my data inside nested hash tables:
$devices = @{"hostname" = @{"Mac Address" = @{"IP Address" = "True or False"}}}
Stores the hostname of the device in $devices
. Inside $hostname
there is a hash table containing all the MAC addresses associated with that hostname. Inside the MAC address, there is a hash table containing all the IP addresses associated with that MAC address.
I've already created a script part that creates a hash table and saves the data. I came across a road block with data export to CSV readable in Excel with the format.
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
etc.
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
}
}
}
source to share
Create custom objects in your inner 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 to output exactly like your example (which I would not recommend), you need to keep track of the previous ones $hostname
and $MAC
and create properties of the empty object in case they match the corresponding current value.
source to share