Bulk clean-up empty VDS networks

Bulk clean-up empty VDS networks

Here is a quick and dirty vSphere PowerCLI script that will help you identify empty networks (those that don't have any VMs attached) in vCenter and as an optional step - delete them from vCenter.

Additionally, the script will check for the word "Trunk" in the network name and skip from deleting any trunk portgroups.

You will need to download and install the appropriate version of PowerCLI from the VMware website in order to run the script.

Write-Host "Connecting to vCenter"
connect-viserver –server your.vcenter.com
$vdses = Get-VDSwitch
$vdpgs_no_vm = @()
foreach ($vds in $vdses)
{
  Write-Host "Retrieving available vDistributed PGs in $vds switch..."
  Write-Host
  $vdpgs = Get-VDPortgroup -VDSwitch $vds
  foreach ($vdpg in $vdpgs)
  {
       if ($vdpg.extensiondata.vm.length -eq 0 -and -not $vdpg.isuplink)
       {
       if (-Not ($vdpg -Match "Trunk")) { 
            $vdpgs_no_vm += $vdpg
            Write-Host $vdpg
            } 
       }
  }
  if ($vdpgs_no_vm.length -ne 0)
  {
  Write-Host "Present are $($vdpgs_no_vm.length) non-trunk portgroups with no VMs attached!"
  Write-Host
  
  $confirmation = Read-Host "Delete $($vdpgs_no_vm.length) non-trunk portgroups? [y/n]"
        if ($confirmation -eq 'y') {
            Write-Host "Removing empty portgroups..."
            Remove-VDPortGroup -VDPortGroup $vdpgs_no_vm
            Write-Host "Done!"
        }
    }
}