PowerCLI – Delete Port Groups using a CSV list

During a recent NSX-T Upgrade project, I was required to migrate VMs from traditional VLAN backed distributed port groups onto NSX-T port groups. This left a large number of port groups that needed to be removed. Fortunately, I was able to export a CSV list and run this quick function to import the CSV list and delete the port groups.

Prior to deleting each PG it will check for existing VMs and display an error if a VM exists before moving on to the next, for example:

The function is as follows

function DeletePortgroups {
Write-Host
$csvlocation = Read-Host " Please enter csv location"
$deletenetworks = Import-Csv $csvlocation

ForEach ($item in $deletenetworks)
{
$pg = $item.PortGroup
if(((Get-VDPortGroup -Name $pg).ExtensionData.Vm).Count -eq 0){
		 Write-Host ".... Portgroup $pg removed" -ForegroundColor Green
		 Get-VDPortGroup -Name $pg | Remove-VDPortGroup -Confirm:$false
}
else{
    Write-Host ".... Portgroup $pg in use by a VM" -ForegroundColor Red
	Start-Sleep -Second 1
	}

}
}

 1,454 total views,  4 views today

Leave a Reply

Your email address will not be published. Required fields are marked *