Listing VMware vSphere host switch ports with a PowerShell (PowerCLI) script
Listing VMware vSphere host switch ports with a PowerShell (PowerCLI) script
PowerShell script here retrieves the network switch ports of VMware vSphere ESXi hosts using the Cisco Discovery Protocol (CDP) & PowerCLI and stores the information in an Excel sheet.
Add-PSSnapin "Vmware.VimAutomation.Core"
Connect-VIServer -Server vcentername.com
$a = New-Object -comobject Excel.Application
$a.visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "HostName"
$c.Cells.Item(1,2) = "NIC#"
$c.Cells.Item(1,3) = "Switch Port Number"
$c.Cells.Item(1,4) = "Cisco Switch ID"
$c.Cells.Item(1,5) = "Address"
$c.Cells.Item(1,6) = "VSwitch name"
$c.Cells.Item(1,7) = "Nic Status"
$d = $c.UsedRange
$d.Interior.ColorIndex = 19
$d.Font.ColorIndex = 11
$d.Font.Bold = $True
$intRow = 2
$vms = get-vmhost
foreach ($vm in $vms){
$vmvps = Get-View $vm
$vmpg = $vm | Get-VirtualPortGroup | Get-NicTeamingPolicy
$vmvps | ForEach-Object {
$NetSys = Get-View $_.ConfigManager.NetworkSystem
foreach($physnic in $NetSys.NetworkInfo.Pnic){
$pnicInfo = $NetSys.QueryNetworkHint($physnic.Device)
foreach($hint in $pnicInfo){
if( $hint.ConnectedSwitchPort ) {
$c.Cells.Item($intRow,1) = $vm.Name
$c.Cells.Item($intRow,2) = $physnic.Device
$c.Cells.Item($intRow,3) = $hint.ConnectedSwitchPort.PortId
$c.Cells.Item($intRow,4) = $hint.ConnectedSwitchPort.DevId
$c.Cells.Item($intRow,5) = $hint.ConnectedSwitchPort.Address
foreach($vp in $vmpg){
if($vp.ActiveNic -eq $physnic.Device){
$c.Cells.Item($intRow,6) = $vp.VirtualPortGroup.Name
$c.Cells.Item($intRow,7) = "Active"
}
elseif($vp.StandbyNic -eq $physnic.Device){
$c.Cells.Item($intRow,6) = $vp.VirtualPortGroup.Name
$c.Cells.Item($intRow,7) = "Standby"
}
}
$intRow = $intRow + 1
}
}
}
}
}
Comments
Post a Comment