# ==========================================
# CLEAN STALE PRINTER PORTS
# Removes unused TCP/IP ports, reports dead ones still in use
# ==========================================

$ports = Get-PrinterPort -ErrorAction SilentlyContinue |
    Where-Object {
        $_.PortMonitor -eq "TCPMON.DLL" -or
        $_.PortMonitor -eq "Standard TCP/IP Port"
    }

$printers = Get-Printer -ErrorAction SilentlyContinue

$usedPorts = @($printers | ForEach-Object { $_.PortName })

$removed = 0
$inUse = 0
$dead = 0

foreach ($port in $ports) {
    $name = $port.Name
    $ip = $port.PrinterHostAddress

    if ($usedPorts -contains $name) {
        # Port is used by a printer — test if alive
        $ping = Test-Connection $ip -Count 1 -Quiet -ErrorAction SilentlyContinue
        if (-not $ping) {
            Write-Host "[WARN] In use but DEAD: $name ($ip)" -ForegroundColor Yellow
            $dead++
        }
        $inUse++
    } else {
        # Port is orphaned — remove it
        try {
            Remove-PrinterPort -Name $name -ErrorAction Stop
            Write-Host "[REMOVED] $name ($ip)" -ForegroundColor Green
            $removed++
        } catch {
            Write-Host "[FAIL] $name - $($_.Exception.Message)" -ForegroundColor Red
        }
    }
}

Write-Host ""
Write-Host "Ports in use: $inUse"
Write-Host "Dead but in use: $dead (remove printer first)"
Write-Host "Orphans removed: $removed"
