[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[其他] 我让chatgpt帮我写了几个批处理,老是有些问题,是我问的不对吗

Rose, [2023/2/23 10:08]
用批处理写一个强制删除位于C盘Windows1目录下的创建于5分钟之内生成的文件夹和文件

ChatGPT CHAT, [2023/2/23 10:08]
以下是一个可以实现您要求的批处理脚本:

@echo off
setlocal

set "target_dir=C:Windows1"

for /f "delims=" %%a in ('dir /b /ad-h /t:c "%target_dir%" ^| findstr /l /c:"<"') do (
    set "dir_path=%target_dir%%%a"
    for /f "delims=" %%b in ('dir /b /a-d /t:c "%dir_path%" ^| findstr /l /c:"<"') do (
        set "file_path=%dir_path%%%b"
        setlocal enableDelayedExpansion
        set "file_create_time=!file_path:=!"
        for /f "usebackq tokens=1-6 delims=/: " %%c in ('dir /tc "!file_path!" ^| findstr /l /c:"<"') do (
            set "create_date=%%f-%%d-%%e"
            set "create_time=%%g"
            set "create_timestamp=!create_date!T!create_time!Z"
        )
        setlocal disableDelayedExpansion
        set "current_time=%date:~10,4%-%date:~4,2%-%date:~7,2"T"%time:~0,2%:%time:~3,2%:%time:~6,2%Z"
        set /a "time_diff=(%current_time:/=-%) - (%create_timestamp:/=-%)"
        if !time_diff! leq 300 (
            echo Deleting file: !file_path!
            del /q "!file_path!"
        )
    )
    rd /s /q "!dir_path!"
)


解释:

1. set "target_dir=C:Windows1" - 设置目标目录的路径。

2. for /f "delims=" %%a in ('dir /b /ad-h /t:c "%target_dir%" ^| findstr /l /c:"<"') do ( - 遍历目标目录下的所有子目录,排除隐藏目录,并使用 findstr 过滤出创建时间在当前时间之前的目录(即创建时间与当前时间相差不超过5分钟的目录)。

3. set "dir_path=%target_dir%%%a" - 获取目录的完整路径。

4. for /f "delims=" %%b in ('dir /b /a-d /t:c "%dir_path%" ^| findstr /l /c:"<"') do ( - 遍历目录下的所有文件,排除目录,并使用 findstr 过滤出创建时间在当前时间之前的文件。

5. set "file_path=%dir_path%%%b" - 获取文件的完整路径。

6. setlocal enableDelayedExpansion - 启用延迟环境变量扩展,以便在循环内部设置变量。

7. set "file_create_time=!file_path:=!" - 将文件路径中的反斜杠替换为双反斜杠,以便在 dir 命令中使用。

8. for /f "usebackq tokens=1-6 delims=/: " %%c in ('dir /tc "!file_path!" ^| findstr /l /c:"<"') do ( - 获取文件的创建时间,并将其转换为 ISO

chatgpt输出转义会把反斜杠\吞掉,所以代码里边的路径不对
建议自己学一点批处理,这样可以看出问题

TOP

回复 2# 老刘1号

好的,我去研究一下,平时都是到处查查复制复制,没有系统的学过

TOP

回复 2# 老刘1号


    老刘好

TOP

回复 1# 复制粘贴怪
我也是  咋一看就发现 反斜杠 消失了

TOP

返回列表