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

PowerShell删除旧文件空目录时多文件夹排除规则失效求助

PowerShell多文件夹排除失效的修复方案

问题根源

你脚本里的($_.FullName -notlike $ExcludedFolders)逻辑存在漏洞:当$ExcludedFolders是数组时,PowerShell只会拿当前路径和数组第一个元素做匹配判断,后续的排除项完全不会生效。要实现“不匹配数组中任何一个文件夹模式”的需求,得换一种判断方式。另外,原脚本的空目录删除逻辑也没考虑排除例外文件夹,就算例外文件夹是空的,也会被误删。

修复后的完整脚本

$limit = (Get-Date).AddDays(-120)
$path = "C:\Users\user\Documents\files"
$ExcludedFileNames = @("*file1*", "*file2*")
$ExcludedFolders = @("*folder1*", "*folder2*")

# 删除超过期限的文件(排除指定文件名和指定文件夹下的文件)
Get-ChildItem -Path $path -Recurse -Force -Exclude $ExcludedFileNames |
Where-Object {
    # 检查当前文件是否不在任何排除的文件夹中
    ($ExcludedFolders | Where-Object { $_.FullName -like $_ }).Count -eq 0 -and
    !$_.PSIsContainer -and
    $_.LastWriteTime -lt $limit
} | Remove-Item -Force

# 删除清理后遗留的空目录(排除指定文件夹)
Get-ChildItem -Path $path -Recurse -Force |
Where-Object {
    $_.PSIsContainer -and
    # 排除例外文件夹,无论是否为空都不删除
    ($ExcludedFolders | Where-Object { $_.Name -like $_ }).Count -eq 0 -and
    # 判断目录是否为空(递归检查是否存在文件)
    (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null
} | Remove-Item -Force -Recurse

关键修改说明

  1. 文件排除逻辑优化:将$_.FullName -notlike $ExcludedFolders替换为($ExcludedFolders | Where-Object { $_.FullName -like $_ }).Count -eq 0,遍历所有排除文件夹模式,只有当前文件路径不匹配任何一个模式时,才会进入删除流程。
  2. 空目录排除逻辑补充:在删除空目录的条件中新增例外文件夹判断,确保指定的例外文件夹无论是否为空,都不会被误删。

如果想让代码更整洁高效,可以把排除判断封装成一个小函数:

function Test-IsExcluded($Item, $ExcludePatterns) {
    return ($ExcludePatterns | Where-Object { $Item.FullName -like $_ }).Count -gt 0
}

之后在Where-Object中直接使用-not (Test-IsExcluded $_ $ExcludedFolders)即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:21:35