Home > database >  Batch - get parameter that include special characters
Batch - get parameter that include special characters

Time:10-20

I know there are many similar question but still not able to make it work.

I have a simple batch that accepts several parameters, one of them is a password which may include special characters.
The batch should run some .exe with the parameters that were sent to the batch. Test.bat param1 param2 !@#$%^&*()_

How should I handle the parameter with special characters ?
I tried using this code and also escaping the special characters with ^^ ^& etc.

  SET PASSWORD=%3

  SET "PASSWORD=%3"

  setlocal enabledelayedexpansion
  SET "PASSWORD=%3"
  echo !PASSWORD!

CodePudding user response:

Important points:

  • Doublequote the parameter Arg1 Arg2 "!@#$%~^&*()_ "
  • Define the variable BEFORE enabling Delayed Expansion to preserve ! characters and any character following / between ! characters.
  • Doublequote the string from the start of the variable name to the end of the variable content, and Use the ~ modifier to remove the surrounding doublequotes during assignment of the expanded argument variable.
@Echo off

 Set "Arg3=%~3"
 IF Defined Arg3 (
  Setlocal EnableDelayedExpansion
  Echo(!Arg3!
 )

 Endlocal
  • Related