Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 324
  • Last Modified:

Batch file: how to call <label> with parameter with & inside?

I have this batch:
set p=abcde
call :mysub %p%
exit /b
:mysub
echo %1

Open in new window

and it works as expected. But if instead of abcde I have a string with & inside,
set p=ab&de
call :mysub %p%
exit /b
:mysub
echo %1

Open in new window

it does not work, as I understand because & is interpreted as escape character. I tried to put various numbers of ^ before & in line 1, but nothing works.

How to get it to work so parameter %1 gets the actual string ab&cd ?
0
Vadim Rapp
Asked:
Vadim Rapp
2 Solutions
 
Randy PooleCommented:
Give this a try
set p=ab^&de
call :mysub %p%
exit /b
:mysub
echo %1

Open in new window

0
 
Steve WhitcherCommented:
Instead of escaping out the individual character, try wrapping the string in double quotes.  For example:

set p="ab&de"
call :mysub %p%
exit /b
:mysub
echo %1

Open in new window


Edit: Actually, I just tested and found that didn't behave as I expected, sorry.  
Instead, include the variable name in the quotes as well, like this:

set "p=ab^&de"
call :mysub %p%
exit /b
:mysub
echo %1

Open in new window

0
 
QlemoC++ DeveloperCommented:
First error: Your set is already failing, only setting p  to ab and then trying to execute de.
Next issue: You need to add ^^ for each instance of providing the value as a string. But that is dangerous, and behaviour strange if not using the correct amount of carets.
One way to get a half-way decent result is:
set "p=ab&de"
call :mysub "%p%"
exit /b
:mysub
echo "%~1"

Open in new window

but in fact it is very difficult to correctly treat some characters in a batch file, because of the simple string replacement strategy it uses. Switch to PowerShell or VBS for such cases ;-).
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now