Windows系统使用bat脚本清空文件和删除目录

@echo off
chcp 65001 >nul
cls

setlocal enabledelayedexpansion

REM 要清空内容的文本文件路径
set file_list[0]=D:\file_list\file-0.txt
set file_list[1]=D:\file_list\file-1.txt
set file_list[2]=D:\file_list\file-2.txt

REM 要删除的目录路径
set dir_list[0]=D:\dir_list\dir-0
set dir_list[1]=D:\dir_list\dir-1
set dir_list[2]=D:\dir_list\dir-2

REM 开始清空文本文件的内容
set count=0
:loop
if defined file_list[!count!] (
    set "file=!file_list[%count%]!"
    if exist "!file!" (
        copy /y nul "!file!" >nul
        if errorlevel 1 (
            echo [失败][清空文件] !file!
        ) else (
            echo [成功][清空文件] !file!
        )
    ) else (
        echo [失败][文件不存在] !file!
    )
    set /a count+=1
    goto :loop
)

REM 开始删除目录
set count=0
:delete_loop
if defined dir_list[!count!] (
    set "dir=!dir_list[%count%]!"
    if exist "!dir!\" (
        rd /s /q "!dir!"
        if errorlevel 1 (
            echo [失败][删除目录] !dir!
        ) else (
            echo [成功][删除目录] !dir!
        )
    ) else (
        echo [失败][目录不存在] !dir!
    )

    set /a count+=1
    goto :delete_loop
)

echo ----------------------------------------------------------------------------------------------------
set /p=任务执行完毕,按任意键退出……<nul
pause >nul

endlocal

REM ========== 说明 ========== REM
REM 1、创建test.bat文件,将上面的代码复制进去,然后双击运行即可。

Copyright © 2025 码农人生. All Rights Reserved