menu

Questions & Answers

How can I make a batch script supply a password with special characters to an external application?

I have a batch script that supplies a username and password to a Windows Service that are required for that service to start. However I am running into breaking issues trying to supply a password that has special characters that are operators in Windows Batch.

The password I am using has special characters and cannot be easily changed to remove them. In this case the special characters / Batch operators that are used are ? and >. Let's say the password is my>passwor?d. The password is stored in a separate secrets file that stores it as "my>passwor?d" with quotes in order to prevent the operators from being interpreted as such.

The password is supplied to an external service as:

%MY_DIRECTORY%\MyService.exe -service %MY_USER% %MY_PWD%

Here's where I run into trouble. %MY_PWD% by default, includes the quotation marks as part of the string. So when I supply it as is, "my>passwor?d" is supplied to the service, which is incorrect, causing it to fail.

When I strip the quotes so that I have my>passwor?d, the correct password, the > and ? operators are run, and cause a breaking error when the batch script is executed.

Finally, when I escape the operators, such that my>passwor?d becomes my^>passwor\?d the script does not fail, but the password supplied to the service INCLUDES the escape characters, which is again wrong, causing the service to fail.

Is there any solution by which I can supply a password (or really any variable) that contains special characters without the escape characters or quotes being passed along with it?

Update: Thanks to the below answer, I managed to solve this with a slight addition that I wanted to note. Due to the variable being assigned in an external shared file, I could not change

set MY_PWD="my>passwor?d" to set "MY_PWD=my>passwor?d"

So I had to deal with scrubbing the quotes. My code ended up looking like:

setlocal enabledelayedexpansion

set MY_PWD=!MY_PWD:"=!

@echo Passing Credentials
/MyService.exe -service %MY_USER% !MY_PWD!
endlocal
Comments:
2023-01-18 00:00:06
Why the ` \ ` backslash? Try my^>passwor?d
2023-01-18 00:00:06
robvanderwoude.com/escapechars.php seemed to suggest that question marks needed to be escaped with backslashes.
2023-01-18 00:00:06
But it's Required only inside the regex pattern of FINDSTR
2023-01-18 00:00:06
Didn't even notice that, thanks.
Answers(1) :

For a "general" solution you can try

set "MY_PWD=my>passwor?d"
for /f "delims= eol=" %%a in ("%MY_PWD%") do (
    %MY_DIRECTORY%\MyService.exe -service %MY_USER% %%~a
)

or

set "MY_PWD=my>passwor?d"
setlocal enabledelayedexpansion
%MY_DIRECTORY%\MyService.exe -service %MY_USER% !MY_PWD!
endlocal
Comments:
2023-01-18 00:00:06
Thanks much! This solved it for me with one small tweak that I edited into my question.