Is there an easy way to define and use a complex literal string in a Windows Batch File without manually escaping each special character?

Viewed 67

Background

I'm trying create a batch file that can copy a file to Azure Storage Explorer using azcopy. I'd like to just copy and paste my SAS key into my batch file without having to locate and escape out all the special characters (&, =, etc.) each time I do so.

My Question

How can I easily define a complex string in a batch file with those characters so that they don't get interpreted and so that I don't have to manually escape them out? Is that even possible? For example, is there some keyword or something that I can add to a set statement that basically tells it, "Hey, all the characters in this variable's value should be used as is without any interpretation"?

Some Resources I've Looked At

In some languages you put variable values in double-quotes to make them literals. I'm not sure how to do it in a batch file.

An Example

Suppose I have this pseudo key:

nifty-11-stuff%3A28GOOBER%3A5&se=2022

Say I want to preserve and use this string EXACTLY as is in a variable, so that if I use it in my batch command later it's unchanged.

I tried this code (with quotes):

@echo off
setlocal EnableDelayedExpansion
set SAS="nifty-11-stuff%3A28GOOBER%3A5&se=2022"
echo %SAS%
pause

My Terminal output in VSCode gives this:

PS D:\git\documentationutilities> cmd /c "d:\git\documentationutilities\test.bat"
"nifty-11-stuffA28GOOBERA5&se=2022"

Notice that the %3A instances are getting interpreted and thus deleted from the final value.

Thank you in advance for any help you can offer.

3 Answers

The percent-signs don't even make it into the string (verify withset var), so I used a text file with your exact string. Delayed expansion avoids the string to be parsed:

@echo off
setlocal EnableDelayedExpansion
<test.txt set /p "var="
set var
echo var=!var!
FOR /f "delims=" %%b IN (%filename%) DO ECHO %%b

if the code can be in a file.

If you need it quoted, then echo "%%b"

If the filename contains spaces, use "usebackqdelims=" and "%filename%"

Related