How to pass html as parameter to a Batch-programm?

Viewed 59

My goal / problem

The following batch program can be used to display my problem:

echo first param: %1 third param: %3
echo '%2'

my goal is to get the following output for param2 (I am aware that it would be a little easier as last parameter but that's not what is needed):

'<body><p style="font-familiy:Arial,Cascadia">MyText</p></body>'

My question is how to call it correctly or change the cmd-code so that the 2nd parameter is not interpreted as multiple parameters

First try: backslashes as escape character

if I escape the double quotes with a backslash like so:

demo p1 "<body><p style=\"font-family:Arial,Cascadia\">MyText</p></body>" p3

the output for param2 is

''"<p style="font-family:Arial'

and the rest of the HTML code is in param3.

Second try: double double quotes as escape character

My second attempt was to escape with double dobule quotes:

demo p1 "<body><p style=""font-family:Arial,Cascadia"">MyText</p></body>" p3

this produces the following output for param2 where the double quotes are not changed at all:

"'<body><p style=""font-family:Arial,Cascadia"">MyText</p></body>'"

The ugly workaround

I managed to get the desired output by replacing from "" to " like so:

set x=%2
echo '%x:""="%'

I wonder if this is the recommended way or if there is an easier way. I read a lot on this subject with https://www.robvanderwoude.com/escapechars.php and http://www.windowsinspired.com/understanding-the-command-line-string-and-arguments-received-by-a-windows-program/ being cited most often but unfortunately neither did help.

1 Answers

As already mentioned, only double quotes can be used to escape a full argument, but the quotes itself can't be escaped inside an argument.
If you still insist on using double quotes in your arguments, the double double quote seems to be one of the best solutions.

But to get and handle the arguments in a safe way, you should switch to delayed expansion, because delayed expanded content isn't parsed anymore (contrary to percent expansion).

set "arg1=%~1"
set "arg2=%~2"
..
setlocal EnableDelayedExpansion
set "arg1=!arg1:""="!"
set "arg2=!arg2:""="!"
echo !arg1! !arg2!
Related