$ErrorActionPreference = 'Stop' $runtimeDir = Join-Path (Join-Path $env:LOCALAPPDATA 'SSHManager') 'runtime' $pidFile = Join-Path $runtimeDir 'app.pid' if (-not (Test-Path $pidFile)) { Write-Output 'SSH Manager 当前未运行。' exit 0 } $rawPid = Get-Content -Path $pidFile -Raw $pidInfo = $null try { $pidInfo = $rawPid | ConvertFrom-Json } catch { $legacyPid = 0 if ([int]::TryParse($rawPid, [ref]$legacyPid)) { $pidInfo = @{ pid = $legacyPid startedAt = 0 } } } if (-not $pidInfo) { Remove-Item -Path $pidFile -Force -ErrorAction SilentlyContinue Write-Output '已清理无效 PID 文件。' exit 0 } $process = Get-Process -Id ([int]$pidInfo.pid) -ErrorAction SilentlyContinue if (-not $process) { Remove-Item -Path $pidFile -Force -ErrorAction SilentlyContinue Write-Output 'SSH Manager 当前未运行。' exit 0 } if ($pidInfo.startedAt -and $process.StartTime) { $processStartedAt = ([DateTimeOffset]$process.StartTime).ToUnixTimeMilliseconds() if ($processStartedAt -ne [int64]$pidInfo.startedAt) { Remove-Item -Path $pidFile -Force -ErrorAction SilentlyContinue Write-Output '已清理过期 PID 文件,未停止任何进程。' exit 0 } } Stop-Process -Id ([int]$pidInfo.pid) -Force Remove-Item -Path $pidFile -Force -ErrorAction SilentlyContinue Write-Output 'SSH Manager 已停止。'