标题: [文件操作] 有请批处理大佬删除指定文件夹以外的特定类型文件 [打印本页]
作者: newyun 时间: 2025-1-10 17:29 标题: 有请批处理大佬删除指定文件夹以外的特定类型文件
批处理删除C盘除了C:\Windows C:\Program Files (x86) C:\Program Files C:\ProgramData这4个文件夹以外其它所有文件夹的*.xls *.xlsm *.xlsx *.xlsb这4种文件,要注意的是排除的4个夹是包含空格的请用引号,这个用gpt4写了一下午,期间改了好多次就是没一次能实现效果的- @echo off
- setlocal enabledelayedexpansion
-
- REM 定义要排除的文件夹
- set "exclude1=C:\Windows"
- set "exclude2=C:\Program Files (x86)"
- set "exclude3=C:\Program Files"
- set "exclude4=C:\ProgramData"
-
- REM 遍历C盘根目录下的所有文件夹
- for /d %%d in ("C:\*") do (
- set "skip=0"
-
- REM 检查当前文件夹是否在排除列表中
- for %%e in ("%exclude1%" "%exclude2%" "%exclude3%" "%exclude4%") do (
- if /i "%%~d"=="%%~e" set "skip=1"
- )
-
- REM 如果不在排除列表中,则删除指定类型的文件
- if "!skip!"=="0" (
- del /q "%%d\*.xls" "%%d\*.xlsm" "%%d\*.xlsx" "%%d\*.xlsb"
- )
- )
-
- echo 删除完成!
- pause
复制代码
这是gpt最终得到的批处理
我觉得应该实现的思路是先排除掉这几个文件夹,然后针对获取到的每个文件夹来执行类似 del 路径*.xls /f /s /q才是正确
作者: new_user 时间: 2025-1-10 17:55
$pathList = @("C:\Windows", "C:\Program Files (x86)", "C:\Program Files", "C:\ProgramData")
$targetExtensionList = @(".xls", ".xlsm", ".xlsx", ".xlsb")
$targetPath = Get-ChildItem -Path C:\ -Depth 0 -Directory | Where-Object {$_.FullName -notin $pathList}
$targetPath | ForEach-Object { Get-ChildItem -Path $_.FullName -File -Recurse -Filter "*.xls*" } | Where-Object {$_.Extension -in $targetExtensionList} | ForEach-Object { Remove-Item -Path $_.FullName }
作者: aloha20200628 时间: 2025-1-10 18:33
本帖最后由 aloha20200628 于 2025-1-10 19:02 编辑
回复 1# newyun
c盘还可能有其他被系统保护的子目录文件,仅用 del 命令不一定能铲动 ...- @echo off &cd /d "c:\" &for /f "delims=" %%d in (
- 'dir /b/ad^|findstr /bixv /c:"windows" /c:"Program Files" /c:"Program Files (x86)" /c:"ProgramData" '
- ) do (del /s/q/f "%%d\*.xls" "%%d\*.xlsm" "%%d\*.xlsx" "%%d\*.xlsb" ) 2>nul
- pause&exit/b
复制代码
作者: aloha20200628 时间: 2025-1-10 18:59
回复 1# newyun
三楼代码已被订正...
作者: newyun 时间: 2025-1-11 10:04
回复 4# aloha20200628
好的我谢谢,谢谢大佬
作者: newyun 时间: 2025-1-11 10:04
回复 3# aloha20200628
隐藏之类的文件夹就不管了
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |