简体   繁体   中英

How can delete all files with a specific extension with cmd batch, excluding 2 specific words? Windows

I want to delete with a batch for windows all files with extension *.jpg in a folder ( test ) and its subfolder, except two files ex: abc.jpg and xyz.jpg that occur several times in different folders.

I tried with

h:

cd test

for /R %%f in (*.jpg) do (if not "%%~xf"=="abc.jpg" if not "%%~xf"=="'xyz.jpg" del "%%~f")

but I failed.

Anyone can help me? Thank you

You might try a FOR loop and check to see if the file name is one that should not be deleted. When you are confident that the correct files would be deleted, remove the echo from the DEL command.

FOR /F "delims=" %%f IN ('DIR /S /B "C:\src\t\*.jpg"') DO (
    IF NOT "%%~nf" == "abc" IF NOT "%%~nf" == "xyz" (
        echo DEL "%%~f"
    )
)

This can also be done in a .bat file script using Powershell. When you are confident that the correct files would be deleted, remove the -WhatIf from the Remove-Item cmdlet.

powershell -NoProfile -Command ^
    "Get-ChildItem -Recurse -Filter '*.jpg' -exclude 'abc.*','xyz.*' |" ^
        "ForEach-Object { Remove-Item -Path $_ -WhatIf }"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM