I want to delete all pdf files in a directory, except for two with file names defined as the variables exception1
and exception2
.
chcp 65001
setlocal ENABLEDELAYEDEXPANSION
set pathname=%~p1
set letter=%~d1
pushd %letter%%pathname%
chcp
set exception1="218-0553.2.pdf"
set exception2="218-0553.2 test.pdf"
pause
dir *.pdf
for %%f in (*.pdf) do (
if /i not "%%~nxf"=="%exception1%" (
if /i not "%%~nxf"=="%exception2%" (
echo Deleting "%%f"
del "%%f"
) else (
echo Keeping "%%f"
)
) else (
echo Keeping "%%f"
)
)
popd
endlocal
This generates an error message:
else was unexpected at this time
I've also tried this, which doesn't work either:
if /i not "%%~nxf"=="%exception1%" and not "%%~nxf"=="%exception2%"
Is there something Im missing?
You are double quoting the exception filenames.
First you have this:
set exception1="218-0553.2.pdf"
set exception2="218-0553.2 test.pdf"
and later
if /i not "%%~nxf"=="%exception1%" (
which will evaluate to
if /i not "%%~nxf"==""218-0553.2.pdf"" (
So changing the exception values to
set exception1=218-0553.2.pdf
set exception2=218-0553.2 test.pdf
will fix it.