2

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.

Philosophene
  • 80
  • 1
  • 7

2 Answers2

1

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.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • Thank you. I didn't know about `PSCustomObject`, but it seems like a great tool for many things. I was also confusing `ForEach` as a alias for `ForEach-Object`. Very confusing! – Philosophene Oct 29 '17 at 08:06
  • 1
    I was able to test and that did it. I ran into a bit of an issue with powershell returning `System.Object[]` when VMs had more than one IP address. I was able to resolved this by using `-join`, like so: `IpAddress = (($_.Section[2].NetworkConnection.IpAddress) -join ',')` – Philosophene Oct 29 '17 at 09:17
1

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.

iRon
  • 20,463
  • 10
  • 53
  • 79
  • I did not know about Flatten-Object. That will be useful in the future as I am always fighting to get info exported out of powershell. Thank you! – Philosophene Oct 29 '17 at 08:44