You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下如何列出指定目录及子目录运行任务并逐一终止

Windows下列出并终止指定目录下的活跃进程

优先推荐使用PowerShell实现,因为它原生支持Windows进程管理,无需额外依赖,功能最完善。以下是三种主流实现方式:


1. PowerShell 实现

功能说明

  • 仅筛选当前用户会话中的进程(避免误操作其他用户进程)
  • 精确匹配指定目录及其子目录下的可执行文件
  • 支持预览进程列表后确认终止

完整脚本

# 设置目标目录(请替换为实际路径)
$targetDir = "C:\Your\Target\Directory"
# 转换为绝对路径,避免相对路径问题
$targetDir = [System.IO.Path]::GetFullPath($targetDir)

# 获取当前用户会话ID
$currentSessionId = (Get-Process -Id $PID).SessionId

# 查询符合条件的进程
$targetProcesses = Get-Process | Where-Object {
    # 过滤无路径的进程(如系统进程)
    $null -ne $_.Path -and
    # 验证进程路径是否在目标目录及其子目录下(忽略大小写)
    $_.Path.StartsWith($targetDir, [System.StringComparison]::OrdinalIgnoreCase) -and
    # 仅保留当前用户会话的进程
    $_.SessionId -eq $currentSessionId
}

# 输出进程列表
if ($targetProcesses.Count -eq 0) {
    Write-Host "未找到目标目录下的活跃进程" -ForegroundColor Green
    exit
}

Write-Host "找到以下目标进程:" -ForegroundColor Cyan
$targetProcesses | Select-Object Id, Name, Path | Format-Table -AutoSize

# 确认终止操作
$confirmInput = Read-Host "是否终止上述所有进程?(Y/N)"
if ($confirmInput -match '^[Yy]$') {
    $targetProcesses | Stop-Process -Force -ErrorAction SilentlyContinue
    Write-Host "已尝试终止所有目标进程" -ForegroundColor Green
} else {
    Write-Host "操作已取消" -ForegroundColor Yellow
}

2. Python 实现

依赖说明

需要安装第三方库 psutil(用于跨平台进程管理):

pip install psutil

完整脚本

import psutil
import os

def get_target_processes(target_dir):
    """获取指定目录下当前用户会话的活跃进程"""
    target_dir = os.path.abspath(target_dir)
    current_session_id = psutil.Process().session_id()
    target_procs = []
    
    for proc in psutil.process_iter(['pid', 'name', 'exe', 'session_id']):
        try:
            proc_info = proc.info
            # 跳过无可执行路径的进程
            if not proc_info['exe']:
                continue
            exe_path = os.path.abspath(proc_info['exe'])
            # 验证路径和会话ID
            if exe_path.startswith(target_dir) and proc_info['session_id'] == current_session_id:
                target_procs.append(proc)
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            # 跳过无法访问的进程(如系统进程)
            continue
    return target_procs

if __name__ == "__main__":
    # 替换为实际目标目录
    target_dir = r"C:\Your\Target\Directory"
    processes = get_target_processes(target_dir)
    
    if not processes:
        print("未找到目标目录下的活跃进程")
    else:
        print("找到以下目标进程:")
        for proc in processes:
            print(f"- PID: {proc.pid}, 名称: {proc.name()}, 路径: {proc.exe()}")
        
        confirm = input("是否终止这些进程?(Y/N): ").strip().lower()
        if confirm == 'y':
            for proc in processes:
                try:
                    proc.kill()
                    print(f"已终止进程: {proc.name()} (PID: {proc.pid})")
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    print(f"无法终止进程: {proc.name()} (PID: {proc.pid}) - 权限不足或进程已结束")
        else:
            print("操作已取消")

3. Batch 脚本实现

注意事项

  • 依赖 WMIC 和 taskkill 命令,Windows系统默认自带
  • 对路径的匹配精度略低于PowerShell/Python,需注意转义字符

完整脚本

@echo off
setlocal enabledelayedexpansion

:: 设置目标目录(请替换为实际路径)
set "TARGET_DIR=C:\Your\Target\Directory"
:: 转义反斜杠,适配WMIC的查询语法
set "ESCAPED_DIR=%TARGET_DIR:\=\\%"

:: 获取当前用户名称
for /f "tokens=2 delims==" %%s in ('wmic computersystem get username /value') do (
    set "CURRENT_USER=%%s"
)

echo 查找当前用户 [%CURRENT_USER%] 会话中路径在 "%TARGET_DIR%" 下的进程:
echo.
wmic process where "ExecutablePath like '%ESCAPED_DIR%\\%%' and Owner='%CURRENT_USER%'" get ProcessId, Name, ExecutablePath /format:table

echo.
set /p "CONFIRM=是否终止这些进程?(Y/N): "
if /i "%CONFIRM%"=="Y" (
    echo.
    echo 正在终止进程...
    :: 遍历并终止符合条件的进程
    for /f "skip=1 tokens=1 delims= " %%p in ('wmic process where "ExecutablePath like '%ESCAPED_DIR%\\%%' and Owner='%CURRENT_USER%'" get ProcessId') do (
        if not "%%p"=="" (
            taskkill /f /pid %%p >nul 2>&1
            if !errorlevel! equ 0 (
                echo 已终止进程 PID: %%p
            ) else (
                echo 无法终止进程 PID: %%p
            )
        )
    )
) else (
    echo 操作已取消
)

endlocal
pause >nul

内容的提问来源于stack exchange,提问作者Spaixn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:40:53