Obtaining CDP info via PowerCLI

There are quite a few posts out there already on this topic and in fact the official VMware KB article has a suggestion on how you can get CDP info via PowerCLI. I didn’t really like the way they presented the code though so I made my own function Get-VMHostNetworkAdapterCDP in the typical style with pipeline input and object output

A typical use case:


Get-VMHost ESXi01 | Get-VMHostNetworkAdapterCDP

 

would see the following output


VMHost NIC Connected Switch PortId ------ --- --------- ------ ------ ESXi01 vmnic0 True Switch01 GigabitEthernet1/0/5 ESXi01 vmnic1 True Switch02 GigabitEthernet2/0/28 ESXi01 vmnic2 True Switch02 GigabitEthernet2/0/29 ESXi01 vmnic3 True Switch04 GigabitEthernet2/0/2 ESXi01 vmnic4 True Switch04 GigabitEthernet2/0/3 ESXi01 vmnic5 False ESXi01 vmnic6 False ESXi01 vmnic7 False


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 MangementAddress = $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 } }