Batch: "%~1" works, but "%~*" is a syntax error. How do I find the equivalent command?

Viewed 1868

Batch: "%~1" works, but "%~*" is a syntax error.

How do I find the equivalent command?

2 Answers

Since %* its batch parameter is a wildcard reference to all the arguments not including %0, you can't use ~ on it, but you can for loop on all arguments and %%~ them, example:

for %%x in (%*) do (
    echo %%~x
)

Also if you need to combine them into single argument you can use setlocal enabledelayedexpansion with this loop:

setlocal enabledelayedexpansion
set args=
for %%x in (%*) do (
  set args=!args! %%~x
)
echo %args:~1%

explain:

  1. !args! is another way to use variable when using setlocal enabledelayedexpansion
  2. %args:~1% remove first space.

And here is example without setlocal enabledelayedexpansion, which does not eat ! symbols from arguments:

set args=
for %%x in (%*) do call :SETARGS %%x
GOTO :END
:SETARGS
set args=%args% %~1
:END
echo %args:~1%

You can remove the quotes from around all parameters and still keep them in one variable using something like the following:

@ECHO off

echo %*

set args=%~1
echo %args%
shift

:Clean
if [%1]==[] goto:End
set args=%args% %~1
shift
goto:Clean

:End

echo %args%

This uses the shift command to cycle through each parameter, remove the quotes and append it to the args environment variable.

Further reading:

Related