找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 16790|回复: 4

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

[复制链接]
发表于 2023-2-23 10:40:04 | 显示全部楼层 |阅读模式
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
发表于 2023-2-23 11:03:44 | 显示全部楼层
chatgpt输出转义会把反斜杠\吞掉,所以代码里边的路径不对
建议自己学一点批处理,这样可以看出问题
 楼主| 发表于 2023-2-23 12:06:58 | 显示全部楼层
回复 2# 老刘1号

好的,我去研究一下,平时都是到处查查复制复制,没有系统的学过
发表于 2023-2-23 20:08:39 | 显示全部楼层
回复 2# 老刘1号


    老刘好
发表于 2023-2-24 09:10:27 | 显示全部楼层
回复 1# 复制粘贴怪
我也是  咋一看就发现 反斜杠 消失了
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-19 05:12 , Processed in 0.017569 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表