{"record":{"id":"771f236ead84d763","repo":"docmirror/dev-sidecar","slug":"port-powershell-pserror-mes","errorCode":null,"errorMessage":"终止占用端口 ${port} 的进程失败。\nPowerShell 方案: ${psError.message}\nCMD 方案: ${cmdError.message}","messagePattern":"终止占用端口 (.+?) 的进程失败。\nPowerShell 方案: (.+?)\nCMD 方案: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/core/src/shell/scripts/kill-by-port.js","lineNumber":52,"sourceCode":"        let killed = false\n        for (const line of lines) {\n          if (!line.includes('LISTENING')) {\n            continue\n          }\n          const parts = line.trim().split(/\\s+/)\n          const pid = parts[parts.length - 1]\n          if (pid && /^\\d+$/.test(pid)) {\n            await exec([`taskkill /f /pid ${pid} /t`], { type: 'cmd', printErrorLog: false })\n            killed = true\n          }\n        }\n        if (!killed) {\n          throw new Error('未找到处于 LISTENING 状态的进程')\n        }\n        return true\n      } catch (cmdError) {\n        // 两种方案都失败，抛出包含原始错误信息的异常\n        throw new Error(\n          `终止占用端口 ${port} 的进程失败。\\n`\n          + `PowerShell 方案: ${psError.message}\\n`\n          + `CMD 方案: ${cmdError.message}`,\n        )\n      }\n    }\n  },\n\n  async linux (exec, { port }) {\n    // 主方案：lsof\n    try {\n      await exec(`kill $(lsof -i:${port} -t 2>/dev/null) 2>/dev/null || true`)\n      return true\n    } catch (_lsofError) {\n      // 备选方案：fuser\n      try {\n        await exec(`fuser -k ${port}/tcp 2>/dev/null || true`)\n        return true","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/docmirror/dev-sidecar/blob/7710cd56cce760c708f30b01d2d4056eb8c402d5/packages/core/src/shell/scripts/kill-by-port.js#L34-L70","documentation":"This is the aggregated failure of kill-by-port on Windows: both the PowerShell plan (Get-NetTCPConnection + Stop-Process) and the CMD plan (netstat -aon parsing + taskkill) failed. The thrown message embeds both underlying error messages (psError and cmdError), so it is the definitive diagnostic for 'could not free the port' on Windows.","triggerScenarios":"Calling the kill-by-port shell script on Windows when: (1) Get-NetTCPConnection is unavailable or the ps invocation itself fails, AND (2) the netstat fallback also fails (empty output / no LISTENING line / taskkill access denied / '未找到处于 LISTENING 状态的进程' from the inner fallback).","commonSituations":"Port held by a process running as another user or SYSTEM (taskkill denied); pwsh not on PATH on stripped-down Windows installs; antivirus blocking taskkill; port not actually listening at all; corporate policy blocking PowerShell script execution.","solutions":["Read the 'PowerShell 方案:' and 'CMD 方案:' lines in the message to identify which stage failed.","If 'access denied' appears, run DevSidecar (or the taskkill) from an elevated prompt: `taskkill /f /pid <pid> /t`.","Manually identify the owner: `netstat -aon | findstr \":<port>\"` then `tasklist /fi \"PID eq <pid>\"`, and close that application.","If PowerShell execution policy blocks scripts, allow it: `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`.","Reboot or use `Stop-Process -Id <pid> -Force` in an admin PowerShell as a last resort."],"exampleFix":null,"handlingStrategy":"fallback","validationCode":"const { execSync } = require('child_process')\nfunction findPortOwner(port) {\n  try {\n    const out = execSync(`powershell -NoProfile -Command \"(Get-NetTCPConnection -LocalPort ${port} -State Listen).OwningProcess\"`, { encoding: 'utf8' })\n    return parseInt(out.trim(), 10) || null\n  } catch { return null }\n}","typeGuard":"function hasKillableOwner(port) {\n  const pid = findPortOwner(port)\n  return Number.isInteger(pid) && pid > 0\n}","tryCatchPattern":"try {\n  await killByPort({ port })\n} catch (e) {\n  const [psMsg = '', cmdMsg = ''] = e.message.split('\\n').filter(l => l.includes('方案'))\n  console.error(`kill-by-port failed. PS: ${psMsg} | CMD: ${cmdMsg}`)\n  if (/denied|拒绝/i.test(e.message)) throw new Error('elevate privileges and retry')\n  if (hasKillableOwner(port)) throw e // process still alive: escalate\n  // else port already free — continue\n}","preventionTips":["Run DevSidecar / the kill with administrator rights when ports are held by other users' or SYSTEM processes.","Keep PowerShell available and its execution policy permissive for the primary path.","Identify the owner with tasklist before killing; close the app gracefully when possible.","Log both sub-errors (the message embeds them) to know which path failed."],"tags":["windows","port","process-kill","powershell","taskkill"],"backgroundTag":"port-already-in-use","analyzedSha":"7710cd56cce760c708f30b01d2d4056eb8c402d5","analyzedAt":"2026-08-31T22:07:07.234Z","schemaVersion":2},"datasetVersion":"2026-08-31T22:30:34.772Z"}