$ErrorActionPreference = "SilentlyContinue" Write-Host "== AIAgent stop ==" -ForegroundColor Cyan function Get-PidsListeningOnPort([int]$Port) { $pids = New-Object System.Collections.Generic.HashSet[int] try { # ForEach-Object 里写 return 会从「外层函数」返回,不能只跳过当前行。 foreach ($raw in (netstat -ano)) { $ln = $raw.Trim() if ($ln -notmatch "LISTENING") { continue } $norm = $ln -replace '\s+', ' ' $parts = $norm.Split(' ') if ($parts.Length -lt 5) { continue } $local = $parts[1] $ci = $local.LastIndexOf(':') if ($ci -lt 0) { continue } if ($local.Substring($ci + 1) -ne "$Port") { continue } $pidStr = $parts[$parts.Length - 1] if ($pidStr -match '^\d+$') { $procId = [int]$pidStr if ($procId -gt 4) { [void]$pids.Add($procId) } } } } catch { } return @($pids) } function Stop-OnPorts([int[]]$ports, [string]$name) { $all = New-Object System.Collections.Generic.HashSet[int] foreach ($p in $ports) { foreach ($listenPid in (Get-PidsListeningOnPort $p)) { [void]$all.Add($listenPid) } } if ($all.Count -eq 0) { Write-Host "[SKIP] ${name}: no listener on ports $($ports -join ',')" -ForegroundColor DarkGray return } foreach ($procId in $all) { if ($procId -le 4) { continue } try { Stop-Process -Id $procId -Force -ErrorAction SilentlyContinue Write-Host "[OK] stopped ${name} PID=$procId" -ForegroundColor Green } catch { Write-Host "[WARN] failed to stop ${name} PID=$procId" -ForegroundColor Yellow } } } # 后端 API(8037 / 8041 备用) Stop-OnPorts @(8037, 8041) "backend-api" # 前端 Vite(3001) Stop-OnPorts @(3001) "frontend-dev" # Redis(6379,仅当监听在本地开发端口时结束;若与其它项目共用请谨慎) Stop-OnPorts @(6379) "redis" # Celery Worker / Beat(不监听端口,需要按命令行匹配) $celeryPatterns = @( @{Pattern='celery\s+-A\s+app\.core\.celery_app\s+worker'; Name='celery-worker'}, @{Pattern='celery\s+-A\s+app\.core\.celery_app\s+beat'; Name='celery-beat'} ) foreach ($cp in $celeryPatterns) { $targets = Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine -match $cp.Pattern } if (-not $targets) { Write-Host "[SKIP] $($cp.Name): no matching process" -ForegroundColor DarkGray } foreach ($p in $targets) { try { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue Write-Host "[OK] stopped $($cp.Name) PID=$($p.ProcessId)" -ForegroundColor Green } catch { Write-Host "[WARN] failed to stop $($cp.Name) PID=$($p.ProcessId)" -ForegroundColor Yellow } } } Start-Sleep -Milliseconds 600 Write-Host "" Write-Host "Port check:" -ForegroundColor Cyan foreach ($port in 3001, 8037, 8041, 6379) { $line = netstat -ano | Select-String ":$port\s+.*LISTENING" | Select-Object -First 1 if ($line) { Write-Host " - ${port}: LISTEN" -ForegroundColor Yellow } else { Write-Host " - ${port}: free" -ForegroundColor Green } } Write-Host "" Write-Host "DONE: stop script finished" -ForegroundColor Green