Public/Remove-specUnassignedTcpPrinterPorts.ps1

function Remove-specUnassignedTcpPrinterPorts {
    <#
    .SYNOPSIS
        Removes unassigned TCP/IP printer ports.
    .DESCRIPTION
        This function identifies and removes any TCP/IP printer ports that are not currently assigned to a printer.
    .EXAMPLE
        Remove-UnassignedTcpPrinterPorts
    #>

    try {
        # Get all TCP/IP printer ports
        $tcpPorts = Get-PrinterPort | Where-Object { $_.PortMonitor -eq 'TCPMON.dll' }

        # Get ports that are currently assigned to printers
        $assignedPorts = Get-Printer | Select-Object -ExpandProperty PortName

        # Find ports that are not assigned to any printer
        $unassignedPorts = $tcpPorts | Where-Object { $assignedPorts -notcontains $_.Name }

        # Remove unassigned TCP/IP ports
        if ($unassignedPorts) {
            [int]$count = 0
            $unassignedPorts | ForEach-Object { $count++ }
            Write-Host "Found $Count unassigned port(s)" -ForegroundColor DarkYellow

            foreach ($up in $unassignedPorts) {
                try {
                    Write-Host "Removing $($up.name)..." -ForegroundColor DarkGray -NoNewline
                    Remove-PrinterPort -Name $up.name -ErrorAction Stop
                    Write-Host 'Removed' -ForegroundColor DarkGreen
                } catch {
                    Write-Error "An error occurred removing the port: $_"
                }
            }
        } else {
            Write-Host 'No unassigned ports found.' -ForegroundColor DarkGray
        }
    } catch {
        Write-Error "An error occurred in the function: $_"
    }
}