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

如何使用PowerShell终止指定文件夹及其子目录下运行的所有程序

PowerShell 终止指定目录及子目录下所有运行程序解决方案

原有方案缺陷

原来的代码只能匹配当前工作目录下的运行程序,无法覆盖子目录内的程序,且必须提前执行cd folder切换到目标目录才能生效,灵活性不足。
原有代码:

Get-Process | ?{$_.path -and (test-path (split-path $_.path -leaf ))} | Stop-Process -Force

改进后方案

改进后的代码支持直接指定目标根目录,无需提前切换工作目录,可匹配目标目录下所有层级子目录中运行的程序:

单次使用版本

直接替换$targetRoot的值为你的实际目标路径即可执行:

# 填写你要操作的目标根目录
$targetRoot = "C:\你的\目标\目录路径"
$normalizedRoot = $targetRoot.Replace('\','\\')
Get-Process | Where-Object {
    $_.Path -and 
    (Test-Path $_.Path) -and 
    ($_.Path -like "$normalizedRoot*")
} | Stop-Process -Force

封装函数版本

如果需要频繁使用,可以封装为自定义函数,调用时直接传入路径即可:

function Stop-ProcessUnderPath {
    param(
        [Parameter(Mandatory=$true)]
        [string]$TargetPath
    )
    # 规范化路径格式,避免转义符问题
    $normalizedPath = (Resolve-Path $TargetPath).Path.Replace('\','\\')
    Get-Process | Where-Object {
        $_.Path -and 
        (Test-Path $_.Path) -and 
        ($_.Path -like "$normalizedPath*")
    } | Stop-Process -Force
}

调用示例:
Stop-ProcessUnderPath -TargetPath "D:\工作\项目目录"


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:45:11