Batch file to handle random % character in FOR LOOP

batch-file, cmd

Solution

Aacini shows a solution that would work with `%` and also `!` but it fails with carets `^`.

But the solution is simple.

First it's necessary to disable the delayed expansion to handle the exclamation marks. The filename is now exactly in the `var` variable. The problems with carets and percents are caused by the `CALL`. This can be solved with the `CALL` itself by use only the second percent expansion phase of the `CALL` by using `%%var%%`.

Setlocal DisableDelayedExpansion
for /R %%a in (*.*) do (
  SET "var=%%~a" 
  call TEST_UPGRADE "%%var%%"
)

The next problem is in the second.bat to display the filename. This should be done with delayed expansion enabled to avoid problems with special characters, or you need always quotes.

set "var=%~1"
setlocal EnableDelayedExpansion
echo Filename: !var!

Problem

I am trying to pass file names as FOR loop parameters to a separate batch file. The problem is, if a file name contains special characters (especially %), the parameter doesnt go to the called script. EG - The `FIRST_SCRIPT.bat` is as follows - ``` cd "C:\theFolder" for /R %%a in (*.*) do call SECOND_SCRIPT "%%~a" ``` The `SECOND_SCRIPT.bat` is as follows - ``` ECHO %1 ``` If a file name contains % eg. "% of STATS.txt", the output ends up being ``` of STATS.txt ``` Which is wrong. I have tried using `Setlocal DisableDelayedExpansion` but with little success ``` Setlocal DisableDelayedExpansion for /R %%a in (*.*) do ( SET "var=%%~a" Setlocal EnableDelayedExpansion call TEST_UPGRADE "%var%" "%%~a" ) ``` There are other stackoverflow answers, but they all need the % character to be known before hand. Since the file names are not in our control, these solutions won't work for us. Is there any way of handling this? Thanks! platform: cmd.exe for Windows XP

Original source