batch file deal with Ampersand (&) in folder name

后端 未结 3 1415
野的像风
野的像风 2021-01-06 14:48

Batch file below:

@echo off
set filelocation=C:\\Users\\myself\\Documents\\This&That
cd %filelocation%
echo %filelocation%
pause

give

3条回答
  •  失恋的感觉
    2021-01-06 15:11

    You need two changes.

    1) The extended set syntax with quotes prefix the variable name and at the end of the content

    2) delayed expansion to use the variable in a safe way

    setlocal enableDelayedExpansion
    set "filelocation=C:\Users\myself\Documents\This&That"
    cd !filelocation!
    echo !filelocation!
    

    Delayed expansiuon works like percent expansion, but it have to be enabled first with setlocal EnableDelayedExpansion and then variables can expanded with exclamation marks !variable! and still with percents %variable%.

    The advantage of the delayed expansion of variables is that the expansion is always safe.
    But like the percent expansion, where you have to double percents when you need it as content, you have to escape exclamation marks with a caret when you use it as content.

    set "var1=This is a percent %%"
    set "var2=This is a percent ^!"
    

提交回复
热议问题