How to get CDP information for all esxi network adapters

It could be very handy to know to what switch, what switch port your esxi network adapters are connected.

get-vmhost | Get-VMHostNetworkAdapterCDP | Select-Object VMHost, NIC, Switch, PortID, connected, ManagementAddress,HardwarePlatform | Export-Csv -notypeinformation -Path c:\temp\cdp.csv

There is no standard method in PowerCLI with name “Get-VMHostNetworkAdapterCDP”.
To make it available you need in Powershell ISE
1. import all powerCLI modules (into command line at bottom of ISE) and press enter
2. copy paste below mentioned function to top windows of ISE and run it
3. enter finally above oneliner into bottom command line prompt

 

function Get-VMHostNetworkAdapterCDP {
<# .SYNOPSIS Function to retrieve the Network Adapter CDP info of a vSphere host. .DESCRIPTION Function to retrieve the Network Adapter CDP info of a vSphere host. .PARAMETER VMHost A vSphere ESXi Host object .INPUTS System.Management.Automation.PSObject. .OUTPUTS System.Management.Automation.PSObject. .EXAMPLE PS> Get-VMHostNetworkAdapterCDP -VMHost ESXi01,ESXi02

 .EXAMPLE
 PS> Get-VMHost ESXi01,ESXi02 | Get-VMHostNetworkAdapterCDP

#>
[CmdletBinding()][OutputType('System.Management.Automation.PSObject')]

Param
 (

[parameter(Mandatory=$true,ValueFromPipeline=$true)]
 [ValidateNotNullOrEmpty()]
 [PSObject[]]$VMHost
 )

begin {

 $ErrorActionPreference = 'Stop'
 Write-Debug $MyInvocation.MyCommand.Name
 $CDPObject = @()
 }

process{

try {
 foreach ($ESXiHost in $VMHost){

if ($ESXiHost.GetType().Name -eq "string"){

 try {
 $ESXiHost = Get-VMHost $ESXiHost -ErrorAction Stop
 }
 catch [Exception]{
 Write-Warning "VMHost $ESXiHost does not exist"
 }
 }

 elseif ($ESXiHost -isnot [VMware.VimAutomation.ViCore.Impl.V1.Inventory.VMHostImpl]){
 Write-Warning "You did not pass a string or a VMHost object"
 Return
 }

$ConfigManagerView = Get-View $ESXiHost.ExtensionData.ConfigManager.NetworkSystem
 $PNICs = $ConfigManagerView.NetworkInfo.Pnic

foreach ($PNIC in $PNICs){

$PhysicalNicHintInfo = $ConfigManagerView.QueryNetworkHint($PNIC.Device)

if ($PhysicalNicHintInfo.ConnectedSwitchPort){

$Connected = $true
 }
 else {
 $Connected = $false
 }

$hash = @{

 VMHost = $ESXiHost.Name
 NIC = $PNIC.Device
 Connected = $Connected
 Switch = $PhysicalNicHintInfo.ConnectedSwitchPort.DevId
 HardwarePlatform = $PhysicalNicHintInfo.ConnectedSwitchPort.HardwarePlatform
 SoftwareVersion = $PhysicalNicHintInfo.ConnectedSwitchPort.SoftwareVersion
 ManagementAddress = $PhysicalNicHintInfo.ConnectedSwitchPort.MgmtAddr
 PortId = $PhysicalNicHintInfo.ConnectedSwitchPort.PortId

}
 $Object = New-Object PSObject -Property $hash
 $CDPObject += $Object
 }
 }
 }
 catch [Exception] {

 throw "Unable to retrieve CDP info"
 }
 }
 end {

 Write-Output $CDPObject
 }
}

ps:

if you need this function and one-liner regularly you can add function into powershell profile and run as alias.