Batch command 'for' is not working

76 Views Asked by At

I have the following line:

for %i in (bin\Setup) do if not %i == setup.exe del %i

This for pretends to delete all files in bin\Setup except from the one called setup.exe, but it's not working...

Any ideas on what I'm doing wrong?

1

There are 1 best solutions below

2
On
for %i in ("bin\Setup\*") do if /i not "%~nxi"=="setup.exe" echo del "%~fi"

Changes made:

  • wildcard included to enumerate all the files in the folder.
  • if is now case insensitive (/i)
  • file references are quoted to avoid problems with spaces
  • only the name and extension of the file (%~nxi) is tested. You can execute for /? to retrieve a full list of modifiers available.
  • removal of the file uses the full path (%~fi) to it

This is written to be executed from command line. Inside a batch file the percent signs need to be escaped, replacing % with %%

for %%i in ("bin\Setup\*") do if /i not "%%~nxi"=="setup.exe" echo del "%%~fi"

del commands are prefixed with a echo so files are not removed, the command is just echoed to console. If the output is correct, remove the echo.