批量删除除部分文件以外的所有文件

时间:2018-12-24 15:14:37

标签: batch-file cmd xcopy del

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

    @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的部分文件?

2 个答案:

答案 0 :(得分:1)

我可能会看一下文件扩展名(使用“ 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”功能的下载器也会保留“完成”文件的名称,您可能不想删除该文件。)

答案 1 :(得分:0)

另一种可能的解决方案(比@mojo的解决方案短):

@echo off
cd /d C:\Users\Toni\Downloads\Downloads
attrib +h *.part
for /f "delims=" %%A IN ('dir /b /A:-H') do del %%A
attrib -h *.part

这将隐藏所有.part文件,删除所有其他文件,然后再次删除hidden属性。