Problem:
How can I get CDP data from network ports in vCenter using PowerCLI?
Solution:
Save the below PowerShell in a file called Get-mVMHostCDPInfo.ps1
param($VMHost) $vmh = Get-VMHost $VMHost If ($vmh.State -ne "Connected") { Write-Output "Host $($vmh) state is not connected, skipping." } Else { Get-View $vmh.ID | ` % { $esxname = $_.Name; Get-View $_.ConfigManager.NetworkSystem} | ` % { foreach ($physnic in $_.NetworkInfo.Pnic) { $pnicInfo = $_.QueryNetworkHint($physnic.Device) foreach( $hint in $pnicInfo ){ # Write-Host $esxname $physnic.Device if ( $hint.ConnectedSwitchPort ) { $hint.ConnectedSwitchPort | select @{n="VMHost";e={$esxname}},@{n="VMNic";e={$physnic.Device}},DevId,Address,PortId,HardwarePlatform } else { Write-Host "No CDP information available." } } } } }
Connect to vCenter:
Connect-VIServer servername
Then run this line to get CDP data from host:
Get-mVMHostCDPInfo.ps1 -VMHost esxi03.earthport.com | Export-Csv -append -path c:\temp\host3.csv
Hello Robin,
Thank you for the script, It works well if you are connected to 1 vcenter at a time, but if you are connected to multiple vcenters, then it is generating duplicate records.
get-view is causing this problem because if we run it without adding the vcenter parameter, it creates views for all connected vcenters.
I modified get-view command like this and it works for multiple vcenters now.
Get-View $vmh.ID -Server $connected_vcenter_1 | …