Skip to content

Instantly share code, notes, and snippets.

@Zsoldier
Created October 7, 2022 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zsoldier/eff448c3f177c6045ffbff73d1258262 to your computer and use it in GitHub Desktop.
Save Zsoldier/eff448c3f177c6045ffbff73d1258262 to your computer and use it in GitHub Desktop.
Automated Method to delete orphaned ports.
$NSXMgr = Read-Host "Enter NSX Manager IP or DNS name:"
$Creds = Get-Credential -Message "Enter NSX username and password"
$PortData = @()
$Segments = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/policy/api/v1/infra/segments/" -SkipCertificateCheck:$true
Foreach ($Segment in $Segments.results){
$Ports = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/policy/api/v1/infra/segments/$($Segment.id)/ports/" -SkipCertificateCheck:$true
$PortData += $Ports.results
While (!([string]::IsNullOrEmpty($Ports.cursor))){
$Ports = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/policy/api/v1/$($Segment.id)/ports?cursor=$($ports.cursor)" -SkipCertificateCheck:$true
$PortData += $Ports.results
}
}
Start-Transcript #Outputs gather data just in case it's needed.
$PortData
$TranscriptLocation = Stop-Transcript #Data saved in text file.
Write-Host "Ctrl-C here to stop and review data captured in transcript file. Otherwise, script will continue to delete 'Operationally DOWN' ports."
Pause -Message "$($TranscriptLocation)"
Start-Transcript
# Uses Manager API to check operational status of port, then delete if that status returns as "DOWN"
# Policy API may be required in future revisions, but not deprecated as of 4.0
$DeletedPorts = @()
Foreach ($port in $PortData){
$portopinfo = Invoke-RestMethod -Authentication Basic -Credential $creds -Method Get -Uri "https://$NSXMgr/api/v1/logical-ports/$($port.id)/status" -SkipCertificateCheck:$true
If ($portopinfo.status -eq "DOWN"){
Invoke-RestMethod -Authentication Basic -Credential $creds -Method DELETE -Uri "https://$NSXMgr/api/v1/logical-ports/$($port.id)?detach=true" -SkipCertificateCheck:$true
Write-Host "Deleted Port id: $($port.id) attached to logical switch id: $($port.logical_switch_id)."
$DeletedPorts += $Port
}
}
Stop-Transcript
Start-Transcript #Output Deleted Ports Data here
$DeletedPorts
Stop-Transcript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment