First time here, but dealing with batch codes from a long time.
I'd like to get some help developing a proper way to get correct parameters in a batch function.
In some functions, I usually need to get the parameters the way they are really passed, not "eating" any comma and not getting the script broked by any special characters.
If the function has one parameter only, it's easy and everything is there in %* the way it should.
But I usually I need to get some auxiliary paramters like variables or paths first and, so, I set the argument that might have some special stuff to the last position.
This is the only way I've found to use and treat complex arguments. But implementing this is always a trouble.
When I thought that I've found a best way by using FOR /F and tokens with *, I got problems when the first arguments (like paths) have spaces (or any other delimiter) because quotes are ignored then.
The only way I can achieve what I want by now is getting each numbered argument and its length then subtracting from all arguments, getting then the "rest argument" that I want, but that is some kind expensive, because I have to call String Len code many times.
Is there a way to use FOR /F delimiting by space but respecting quoted parameters with spaces?
Or anyone else knows a better and proper way of achieving what I want?!
Here's some code to illustrate the problem:
Code: Select all
@ECHO OFF
:: When no space in first arguments everything works
CALL :MyFunc arg1 argument2 c:\path\to\arg3 c:\path\toarg4 ,run, anything "here" even specials "&" like "|<>" and single" quotes
:: But spaces broke first arguments
CALL :MyFunc arg1 "argument 2" c:\path\to\arg3 "c:\spaced path\to arg4" ,run, anything "here" even specials "&" like "|<>" and single" quotes
GOTO :EOF
:MyFunc
SETLOCAL EnableDelayedExpansion
ECHO Checking if everything is there
ECHO %*
ECHO.
SET params=%*
ECHO Traditional way of parsing parameters works for first params:
ECHO 1:%1 2:%2 3:%3 4:%4
ECHO But how to get rest this way?
ECHO.
ECHO Trying to get through FOR /F and tokens with * to get rest
FOR /F "tokens=1,2,3,4*" %%a IN ("!params!") DO SET "arg1=%%~a" & SET "arg2=%%~b" & SET "arg3=%%c" & SET "arg4=%%~d" & SET "argrest=%%e"
ECHO It will work for non spaced first params but not for parameters with spaces quoted because delims is space
ECHO Parsing Desired Arguments With FOR:
ECHO 1:!arg1! 2:!arg2! 3:!arg3! 4:!arg4! Rest:!argrest!
ECHO.
GOTO :EOF