Hey everyone so I have the following batch variable %~4
which is a users username. Currently, I am having a problem because I had a user signup with the username Scott123! the ! is not read correctly. I tried escaping it like this "%~4"
and that works on most characters but not the ! character. Has anyone come up with a solution for this?

- 434
- 1
- 9
- 24
-
It could be helpful to see how you obtain your username input, if it is done inside the batch file. Or to see what is done with it later on where the problem with the unescaped exclamation mark occurs. Please add some code snippets if applicable. – Antares May 05 '20 at 18:57
2 Answers
You can try set username="%~4:!=^^!"
to replace any !
with an escaped exclamation mark (maybe you need to assign %~4
to another variable first).
You might need to consider replacing < > % | = , : & CON LPT1
and other keywords/symbols that are special in batch files, to prevent "batch file injection" ;)
If I recall correctly, only !
needs a double caret as escape symbol (it is used for denoting the delayed expansion variables normally). The percent symbol is also special, it needs another percent symbol to be escaped %%
. If you need to escape the caret as well, things will get tricky, I assume.
ss64.com might help you to get a complete overview of all the special cases: https://ss64.com/nt/syntax-esc.html
String replacement in variables is described in the help for set
. Executeset /?
on a command line window to read it. Or try ss64 as well, might be the more exhaustive read (https://ss64.com/nt/set.html).
If nothing works or is to much effort inside the batch file, you need to escape these characters beforehand somewhere else. Better yet, forbid them as username input entirely. Then the need for escaping is lifted.

- 605
- 3
- 14
One of the ways I got it to work was commenting out SETLOCAL ENABLEDELAYEDEXPANSION and putting "" around the variable.

- 434
- 1
- 9
- 24