Philosophene
Philosophene

Reputation: 190

Using Export-Csv

I am having some trouble getting the formatting correct for my script. I am trying to use powercli with VMware to pull host name and IP info and from a vApp and export it to CSV.

So far I have:

$vapp = Get-CIVApp -name name_of_vApp
$vms = $vapp.ExtensionData.Children.vm
$output = foreach ($vm in $vms) {$vm | select-object -Property Name;$vm.Section[2].NetworkConnection | select-object -Property IpAddress,ExternalIpAddress;} 
$output | export-csv -Path c:\temp\test.csv -NoTypeInformation

The problem, seems to be the line where I assign a value to $output. For some reason it doesn't add the IP info, even though that works outside of the function or even inside the function without $vm.name. It just gives me the machine names separated by blank lines equal to the number of IP addresses that server has.

My ultimate goal is to have a three column table with the name of the server, the internal IP address and the external IP address. Any help would be appreciated.

Thanks in advance.

Upvotes: 2

Views: 545

Answers (2)

iRon
iRon

Reputation: 23663

The problem is that after the second Select you still working with the (filtered) $vm object and not $vm.secton[2], try to $vm | Flatten-Object first.

Upvotes: 1

Mark Wragg
Mark Wragg

Reputation: 23355

I think the problem might be because you are outputting two objects instead of one in each iteration. PowerShell generally works best when you return a single object to the pipeline. You can do so in this instance by using the [pscustomobject] type with a hashtable of properties.

I also think it makes sense to use ForEach-Object instead of ForEach as then you can pipe the output directly on to Export-CSV:

$vapp = Get-CIVApp -name name_of_vApp
$vms = $vapp.ExtensionData.Children.vm

$vms | ForEach-Object {
    [pscustomobject]@{
        Name = $_.name
        IpAddress = ($_.Section[2].NetworkConnection.IpAddress)
        ExternalIpAddress = ($_.Section[2].NetworkConnection.ExternalIpAddress)
    }
} | Export-CSV -Path c:\temp\test.csv -NoTypeInformation 

Note that I don't know if the way you are collecting the IPAddress and ExternalIPAddress properties is necessarily valid here, and don't currently have somewhere to test this part.

Upvotes: 1

Related Questions