1

I would like to process and rewrite parameters passed to a windows bat file and then call another bat file. More precisely: I want to replace backslashes in parameters by slashes.

Example: first.bat C:\Users\myself\test.txt anotherParam should call second.bat C:/Users/myself/test.txt anotherParam

My attempt so far:

@echo off
setlocal ENABLEDELAYEDEXPANSION

set argCount=0
for %%x in (%*) do (
   set /A argCount+=1      
   call set argVec[!argCount!]=%%~x:\=/%%
)

echo Number of processed arguments: %argCount%

for /L %%i in (1,1,%argCount%) do echo %%i- "!argVec[%%i]!"

call second.bat %argVec%

Problems:

  • String replacement in loop does not work as expected
  • Call of second.bat does not submit parameters

Thank you for suggestions on this topic.

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
Rüdiger
  • 91
  • 5
  • Sub-string substitution only works with normal environment variables but not with `for` meta-variables, like `%%x` in your code… – aschipfl Dec 21 '21 at 07:43
  • 2
    Perhaps this simple solution may work: `set "params=%*"` and `call second.bat %params:\=/%` – Aacini Dec 21 '21 at 11:36

1 Answers1

2

For simple parameters the solution can be simple

REM *** Avoid problems with ! in parameters
setlocal DisableDelayedExpansion
set "args=%*"

REM *** Use delayed expansion to avoid problems in search/replace
setlocal EnableDelayedExpansion

set "args=!args:\=/!"

REM *** Set delayed expansion to the "default" for second.bat
setlocal DisableDelayedExpansion
call second.bat %%args%%

BUT, if the parameters are more complex, containing a mix of quotes, ampersands or carets, it gets nasty.

Then you need How to receive even the strangest command line parameters?

If you want to handle even newlines, then you need the syntax-error-technique

And then you need to modify the retrieved arguments, so they can be used for calling a secondary batch file.

At least:

set "args=!args:^=^^!"
set "args=!args:&=^&!"
set "args=!args:|=^|!"
set "args=!args:<=^<!"
set "args=!args:>=^>!"
set ^"args=!args:"=^"!"
jeb
  • 78,592
  • 17
  • 171
  • 225