Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

windows - Escape percent in bat file

I was trying to write a VPN dialer/disconnector using a batch file, but I got stuck. After some investigation I found that the presence of % in the password is not playing well.

Here is the code

@echo OFF
SET SWITCHPARSE1=%1
SET SWITCHPARSE2=%2
REM echo %SWITCHPARSE1%
SHIFT
SHIFT
IF "SWITCHPARSE1" == "" goto Usage
IF "SWITCHPARSE1" == "/?" goto Usage
IF "SWITCHPARSE2" == "" goto Usage
IF "SWITCHPARSE2" == "/?" goto Usage


IF "%SWITCHPARSE1%" == "sl" (
    IF "%SWITCHPARSE2%" == "conn" (
        echo "inside sl conn"
        rasdial sl employee1 K%%Pxev3=)g:{#Swc9
        goto end
    ) ELSE IF "%SWITCHPARSE2%" == "disconn" (
        rasdial sl /disconnect
        goto end
    ) ELSE (
        goto Usage
    )
) ELSE IF "%SWITCHPARSE1%" == "off" (
        IF "%SWITCHPARSE2%" == "conn" (
        rasdial Office employee1 office123
        goto end
    ) ELSE IF "%SWITCHPARSE2%" == "disconn" (
        rasdial Office /disconnect
        goto end
    ) ELSE (
        goto Usage
    )
) ELSE (
    goto Usage
)

:Usage
echo "Usage is vpnconn.bat /[sl|off] /[conn|disconn]"

:end

In the above script I am trying to escape % using % (i.e. %%, reference from here), but the bat script gives g:{#Swc9 was unexpected at this time..

To root cause further, I tried to double %% (escape %) in a different batch file, and it worked:

@echo OFF
rasdial sl employee1 K%%Pxev3=)g:{#Swc9

Why does the same script when integrated to work with different connections not work?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two %% equals to one %. That's right (but only in a script, not directly in the cmd), no need to use the escape operator ^.

But you are missing the agrupation operator ). That's the problem; the IF closes when it finds the ) at your command.

Use this:

rasdial sl employee1 K%%%%Pxev3=^)g:{#Swc9

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...