windows上删除文件或者目录
@echo off
:: 切换代码页为 UTF-8,解决中文乱码
chcp 65001 >nul
setlocal enabledelayedexpansion

:: --- 配置区域 ---
set "targetDir=D:\Code\XXXX"

:: 这里支持通配符,例如 hgsl-module-*.iml 或 *.tmp
:: set "targetPattern=hgsl-module-*.iml"
set "targetPattern=${project.build.directory}"

:: 模式设置:1 为仅删除文件夹,2 为仅删除文件,3 为两者都删
set "mode=1"
:: ---------------

set /a count=0

echo 正在搜索模式: "%targetPattern%" (模式: %mode%)
echo 目标路径: "%targetDir%"
echo ---------------------------------------

if not exist "%targetDir%" (
    echo [错误] 找不到指定的路径。
    pause
    exit /b
)

:: 使用 dir /s /b /a 结合通配符进行递归查找
for /f "delims=" %%f in ('dir "%targetDir%\%targetPattern%" /s /b /a 2^>nul') do (

    set "isDir=0"
    :: 判断是否为目录的技巧:路径加斜杠是否存在
    if exist "%%f\" set "isDir=1"

    if "!isDir!"=="1" (
        if "%mode%"=="1" ( call :deleteItem "%%f" "DIR" )
        if "%mode%"=="3" ( call :deleteItem "%%f" "DIR" )
    ) else (
        if "%mode%"=="2" ( call :deleteItem "%%f" "FILE" )
        if "%mode%"=="3" ( call :deleteItem "%%f" "FILE" )
    )
)

echo ---------------------------------------
if %count% equ 0 (
    echo [提示] 未找到任何匹配 "%targetPattern%" 的项目。
) else (
    echo [成功] 清理完成,共处理了 %count% 个项目。
)
pause
exit /b

:: --- 统一删除子程序 ---
:deleteItem
if "%~2"=="DIR" (
    echo [%time%] 正在删除目录: %1
    rd /s /q %1 2>nul
) else (
    echo [%time%] 正在删除文件: %1
    del /f /q %1 2>nul
)
set /a count+=1
goto :eof
暂无评论

发送评论 编辑评论


				
上一篇