Batch file parameter with spaces, double quotes, pipes

后端 未结 2 1900
走了就别回头了
走了就别回头了 2021-01-03 00:36

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 pa

2条回答
  •  温柔的废话
    2021-01-03 01:43

    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

提交回复
热议问题