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

mauro

New Member
#1
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
Mã:
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
 

Admin

Administrator
Thành viên BQT
#2
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.
Mã:
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.
Mã:
powershell -NoProfile -Command ^
    "Get-ChildItem -Recurse -Filter '*.jpg' -exclude 'abc.*','xyz.*' |" ^
        "ForEach-Object { Remove-Item -Path $_ -WhatIf }"
 
Top