首页 > 解决方案 > 批量删除除部分文件外的所有文件

问题描述

我有一个批处理文件,它不断检查目录中是否有任何文件:

    @echo off
    cls
    mode 15,5 
    cd C:\Users\Toni\Downloads\
    goto mark
:mark
    set var=2
    dir /b /a "Downloads\*" | >nul findstr "^" && (goto exin) || (goto mark1)
    goto mark
:mark1
    cls
    @ping -n 10 localhost> nul
    goto mark
:exin
    start /B C:\Users\Toni\Downloads\Test\download.bat
    exit

如果此文件夹中有任何文件,它会移动它们。

    @echo off
cls
cd C:\Users\Toni\Downloads\Downloads        
        xcopy /Y C:\Users\Toni\Downloads\Downloads\*.rar C:\Users\Toni\Downloads\Archive
        xcopy /Y C:\Users\Toni\Downloads\Downloads\*.zip C:\Users\Toni\Downloads\Archive
        xcopy /Y C:\Users\Toni\Downloads\Downloads\*.exe C:\Users\Toni\Downloads\Setups_usw
        xcopy /Y C:\Users\Toni\Downloads\Downloads\*.msi C:\Users\Toni\Downloads\Setups_usw
        xcopy /Y C:\Users\Toni\Downloads\Downloads\*.mp3 E:\-_MUSIC_-\Musik
        xcopy /Y C:\Users\Toni\Downloads\Downloads\*.wav E:\-_MUSIC_-\Musik
        xcopy /S /E /Y /EXCLUDE:C:\Users\Toni\Downloads\Test\excludedfileslist.txt C:\Users\Toni\Downloads\Downloads\*.* C:\Users\Toni\Downloads\Sonstiges
    goto err        
    :err
    if errorlevel 1 ( dir /arashd >> "C:\Users\Toni\Downloads\Test\somefile.txt" 2>&1  ) else ( del /[!*.part] * )
    goto end
    :end
    start /B C:\Users\Toni\Downloads\Test\run.cmd
    exit

但是,我不想移动正在下载的文件(即,我不想移动带有.part扩展名的部分文件)。

我尝试使用del命令的参数,如下所示:

del /[!*.part] *

但它似乎不起作用。

如何避免移动带有.part扩展名的部分文件?

标签: batch-filecmdxcopydel

解决方案


我可能会查看文件扩展名(使用“替换 FOR 变量”)。

SET "TARGET_DIR=C:\Users\Toni\Downloads\Downloads"
FOR /F "delims=" %%f IN ('dir /b "%TARGET_DIR%"') DO (
    REM  Ensure it doesn't have '.part' as an extension.
    IF NOT "%%~xf"==".part" (
        REM  Ensure there's not a corresponding ".part" file.
        IF NOT EXIST "%TARGET_DIR%\%%~f.part" (
            DEL "%TARGET_DIR%\%%~f"
        )
    )
)

这将删除任何TARGET_DIR没有“.part”作为文件扩展名或具有相应“.part”文件的文件。(根据我的经验,执行“.part”操作的下载器也会保留“已完成”文件的名称,您可能不想删除它。)


推荐阅读