下面的批处理文件:
@echo off
set filelocation=C:UsersmyselfDocumentsThis&That
cd %filelocation%
echo %filelocation%
pause
给出如下输出:
'That' is not recognized as an internal or external command,
operable program or batch file.
The system cannot find the path specified.
C:UsersmyselfDocumentsThis
Press any key to continue . . .
考虑到我不能更改文件夹名称,我如何处理"&"
你需要做两个改变。
1)扩展集语法,在变量名前面加上引号,并在内容的末尾加上引号
2)延迟扩展以安全的方式使用变量
setlocal enableDelayedExpansion
set "filelocation=C:UsersmyselfDocumentsThis&That"
cd !filelocation!
echo !filelocation!
延迟扩展的工作原理类似于百分比扩展,但它必须首先启用setlocal EnableDelayedExpansion
,然后变量可以使用感叹号!variable!
展开,仍然使用百分比%variable%
。
但是,就像百分号展开一样,当你需要它作为内容时,你必须将百分号加倍,当你将它用作内容时,你必须用一个插入符号转义感叹号。
set "var1=This is a percent %%"
set "var2=This is a percent ^!"
与Jeb不同,我认为您不需要延迟展开以安全的方式使用变量。适当的报价可以满足大多数用途:
@echo off
SETLOCAL EnableExtensions DisableDelayedExpansion
set "filelocation=C:UsersmyselfDocumentsThis&That"
cd "%filelocation%"
echo "%filelocation%"
rem more examples:
dir /B "%filelocation%*.doc"
cd
echo "%CD%"
md "%filelocation%sub&folder"
set "otherlocation=%filelocation:&=!%" this gives expected result
SETLOCAL EnableDelayedExpansion
set "otherlocation=%filelocation:&=!%" this gives unexpected result
ENDLOCAL
pause
此外,这是通用的解决方案,而延迟扩展可能会在处理字符串中出现!
感叹号的情况下失败(例如上面的最后一个set
命令)。
有两种方法:
。引用字符串;例句:
set "filelocation=C:UsersmyselfDocumentsThis&That"
b。使用转义字符;例如:
set filelocation=C:UsersmyselfDocumentsThis^&That
要将该路径与cd
命令一起使用,请将其括在引号中。
cd /d "%filelocation%"