windowsbatch-filecmdcommand-line-argumentsdelayedvariableexpansion

Passing arguments with special characters to batch script while delayedexpansion enabled


I need to call a script which accepts password as one of its arguments. Whenever the password contains , it is treated as a delimiter and the password will be split into two arguments and when it contains ! all the special characters are omitted. I have tried enclosing them in ', " and preprocessing the password to escape with both ^ and ^^. Unfortunately, nothing worked. How to preserve these special characters in the password?


Solution

  • You are right, delayed expansion has to be turned of (temporarily) for that to work properly. The ! has to be escaped (for the delayed part later) and quoting takes care of the rest:

    @echo off
    setlocal enabledelayedexpansion
    
    REM --- get parameter ---
    setlocal disabledelayedexpansion
    set "x=%~1"
    endlocal & set "x=%x:!=^!%"
    REM --- end get param ---
    
    set x
    echo "!x!"
    

    Output:

    C:\TEST>test.bat "pass,!<& %|>word"
    x=pass,!<& %|>word
    "pass,!<& %|>word"
    

    The main trick is the line endlocal & set "x=%x:!=^!%". The set command is still parsed without delayed expansion, but executed after endlocal (as the whole line is parsed before anything gets executed - yes, strange thing...)