Skip to main content

Script to collect LLDP Information of all the hosts connected to vCenter

 

Challenge: To have a clean inventory of host to switch mapping, we had to gather the lldp information of all the ESXi hosts. It would be easier if the hosts are a few/ in a single digit. 

We had to find an easy and automated script which can generate the output.

 Pre-requisites:

1) Requires power-cli to be installed.

2) Install-Module -Name VMware.PowerCLI -Scope CurrentUser 

Powershell script:

 1) To ignore ssl certificate error

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$true

 2) Script to connect to vCenter and provide valid credentials, and the script will provide the output in a csv format to the provided location, which can be customized.

 # Array of vCenter Server names or IP addresses
$vCenterServers = @("192.168.1.62") # Add all your vCenter Servers here

# Output file path
$OutputPath = "C:\Users\asyed\Documents\ESXi_LLDP_Report1.csv" # Change this to your desired output path

# --- Script Start ---

Write-Host "Connecting to vCenter Server(s)..." -ForegroundColor Green

# Connect to all specified vCenter Servers
# Using -Force to bypass certificate warnings for lab/test environments.
# In production, ensure proper certificate handling.
try {
    Connect-VIServer -Server $vCenterServers -WarningAction SilentlyContinue -ErrorAction Stop
    Write-Host "Successfully connected to vCenter Server(s)." -ForegroundColor Green
}
catch {
    Write-Error "Failed to connect to vCenter Server(s). Error: $($_.Exception.Message)"
    exit
}

$lldpReport = @()

Write-Host "Gathering LLDP information from ESXi hosts..." -ForegroundColor Green

# Get all ESXi hosts
$allEsxiHosts = Get-VMHost # Renamed the collection variable for clarity

if ($allEsxiHosts.Count -eq 0) {
    Write-Warning "No ESXi hosts found in the connected vCenter Server(s)."
}
else {
    # CHANGE THIS LINE: Use a different variable name for the loop, e.g., $esxiHost
    foreach ($esxiHost in $allEsxiHosts) {
        Write-Host "Processing host: $($esxiHost.Name)..." -ForegroundColor Cyan

        try {
            # Get the NetworkSystem view for the host
            $networkSystem = Get-View $esxiHost.ExtensionData.ConfigManager.NetworkSystem

            # Get physical NICs
            $physicalNics = $esxiHost.ExtensionData.Config.Network.Pnic

            if ($physicalNics.Count -eq 0) {
                Write-Warning "No physical NICs found for host $($esxiHost.Name)."
                continue
            }

            foreach ($pnic in $physicalNics) {
                $pnicDevice = $pnic.Device
                $networkHint = $null

                try {
                    $networkHint = $networkSystem.QueryNetworkHint($pnicDevice)
                }
                catch {
                    Write-Warning "Could not retrieve network hint for $($esxiHost.Name) - $($pnicDevice). Error: $($_.Exception.Message)"
                    continue
                }

                if ($networkHint) {
                    foreach ($hint in $networkHint) {
                        if ($hint.LldpInfo) {
                            $lldpInfo = $hint.LldpInfo
                            $managementAddress = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "Management Address"}).Value
                            $systemName = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "System Name"}).Value
                            $systemDescription = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "System Description"}).Value
                            $portDescription = ($lldpInfo.Parameter | Where-Object {$_.Key -eq "Port Description"}).Value
                            $chassisId = $lldpInfo.ChassisId
                            $portId = $lldpInfo.PortId

                            $lldpEntry = [PSCustomObject]@{
                                VMHostName          = $esxiHost.Name
                                VMHostIP            = (Get-VMHostNetworkAdapter -VMHost $esxiHost | Where-Object {$_.ManagementTrafficEnabled -eq $true}).IP # Get management IP
                                PhysicalNic         = $pnicDevice
                                LLDP_ChassisID      = $chassisId
                                LLDP_PortID         = $portId
                                LLDP_PortDescription= $portDescription
                                LLDP_SystemName     = $systemName
                                LLDP_SystemDescription = $systemDescription
                                LLDP_ManagementAddress = $managementAddress
                            }
                            $lldpReport += $lldpEntry
                        }
                        elseif ($hint.ConnectedSwitchPort) {
                            Write-Verbose "CDP information found for $($esxiHost.Name) - $($pnicDevice). LLDP not present."
                        }
                        else {
                            Write-Verbose "No LLDP or CDP information found for $($esxiHost.Name) - $($pnicDevice)."
                        }
                    }
                }
            }
        }
        catch {
            Write-Error "An error occurred while processing host $($esxiHost.Name). Error: $($_.Exception.Message)"
        }
    }
}

Write-Host "Exporting LLDP information to CSV: $($OutputPath)..." -ForegroundColor Green

if ($lldpReport.Count -gt 0) {
    $lldpReport | Export-Csv -Path $OutputPath -NoTypeInformation -UseCulture
    Write-Host "LLDP report generated successfully at: $($OutputPath)" -ForegroundColor Green
}
else {
    Write-Warning "No LLDP information was collected to export."
}

Write-Host "Disconnecting from vCenter Server(s)..." -ForegroundColor Green
Disconnect-VIServer -Confirm:$false

Write-Host "Script finished." -ForegroundColor Green 

# --- Script End --- 

 

3) Once you get the output, return the invalid certificate action to false by running below command. 

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false 

Comments

Popular posts from this blog

Create a vCenter role using vCenter MOB

 Requirement: Finding a way to automate the creation of Role for any services with its permissions. Example: Citrix service account to be integrated with vCenter. Steps: 1) Login to vCenter : https://192.168.1.68/mob  2) Click on 'Content'                3) Click on Authorization Manager                                     4) Click on  'AddAuthorizationRole'                             5) Provide name in name field & privId in xml format & Click Invoke Method                        This should give you a return value and then the Role will be reflected on vCenter. 

Script to Collect the BMC/OOB/CIMC IP Address of ESXi hosts connected to vCenter

 Requirement: We needed to collect all the iDRAC/ILO/CIMC/OOB/BMC IPs of the ESXi host connected to vCenter Note: Create a directory and update the path. Script: # Prompt for vCenter $vcenter = Read-Host "Enter vCenter IP or FQDN" $cred = Get-Credential # Output file $OutputPath = "C:\Users\TestUser\Documents\ESXi_Full_Report.csv" # Connect Connect-VIServer -Server $vcenter -Credential $cred -WarningAction SilentlyContinue Write-Host "Connected to vCenter. Gathering data..." -ForegroundColor Green $report = @() $vmhosts = Get-VMHost foreach ($vmhost in $vmhosts) {     Write-Host "Processing host: $($vmhost.Name)" -ForegroundColor Cyan     $view = Get-View $vmhost.Id     # --- SERIAL NUMBER LOGIC ---     $serial = $view.Hardware.SystemInfo.SerialNumber     if (-not $serial) {         foreach ($id in $view.Summary.Hardware.OtherIdentifyingInfo) {             if ($id.IdentifierType.Key ...

System Recovery Partition Disk Blocks The Extension of Windows Disk - Sysprep Issues

Requirement : Windows Activated Template on vCenter  Issue : After the windows is installed, system recovery partition end up created next to windows disk.  Resolution Credit : Mohammed Junaid Ahmed                           Resolution :  1) Create a VM using standard procedure on vCenter  2) Power ON the VM and follow below screen instructions  Click Next   Click on ' Repair your computer '  Click on Troubleshoot       Click on Command Prompt     You should see the command prompt Begin with Diskpart   Click Turn off your PC Restart your computer and continue windows installation, and you will see the disk partitions as below