开发者

Batch file parameter with spaces, double quotes, pipes

I have开发者_开发技巧 a batch file that needs to be passed a parameter that will include pipes and spaces. Because of the spaces, double quotes need to be attached to the parameter when passing it in. I need to strip off those double quotes and echo the parameter. Normally, using the ~ would let me do this, but I think something about the specific parameters I'm passing in causes a problem. If I do this:

[test1.bat]

call test2.bat "Account|Access Level|Description"

[test2.bat]

echo %1
echo %~1

And run test1.bat, I get this output:

"Account|Access Level|Description"
'Access' is not recognized as an internal or external command, operable program or batch file.

So how do I remove the double quotes and still have a usable variable?


You could use delayed expansion, because it doesn't care about special characters.
The only problem is to get parameter content into a variable, as it can only transfer via a percent expansion.
But in your case this should work.

@echo off
setlocal DisableDelayedExpansion
set "str=%~1"
setlocal EnableDelayedExpansion
echo !str!

Remark, I disable first the delayed expansion, so the ! and ^ aren't modified by the expansion of %1

EDIT: The delayed expansion can be disabled or enabled with

setlocal DisableDelayedExpansion
setlocal EnableDelayedExpansion

If enabled, it adds another way of extending variables (!variable! instead of %variable%), primary to prevent the parenthesis block effect of variables (described at set /?).

But the expansion with !variable! also prevents the content of any further parsing, because the delayed expansion is the last phase of batch line parsing.
In detail it is explained at how does the windows command interpreter cmd exe parse scripts


@echo off
if "%~2"=="" (
    call %0 "Account|Access Level|Description" dummy
) ELSE (
    setlocal ENABLEEXTENSIONS
    for /F "tokens=*" %%A IN ("%~1") DO @echo.%%A
)

Not exactly pretty, but it works. Dealing with special characters is always a pain in batch files...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜