下面的批处理文件:
@echo off
set filelocation=C:\Users\myself\Documents\This&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:\Users\myself\Documents\This
Press any key to continue . . .
考虑到我无法更改文件夹名称,如何处理“&”
您需要进行两项更改。
1)带引号的扩展集语法在变量名称前面和内容末尾
2)延迟扩展以安全的方式使用变量
setlocal enableDelayedExpansion
set "filelocation=C:\Users\myself\Documents\This&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:\Users\myself\Documents\This&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
命令),则延迟扩展可能会失败。
有两种方法:
a.引用字符串;例如:
set "filelocation=C:\Users\myself\Documents\This&That"
b.使用转义字符;例如:
set filelocation=C:\Users\myself\Documents\This^&That
要通过
cd
命令使用该路径,请将其用引号引起来。
cd /d "%filelocation%"
除了“&”之外,还有其他几个字符如果不加以防范,也会导致批处理脚本失败。 其中包括大于 (>),它是输出重定向符号;小于 (<), which is the input redirect symbol; vertical bar (|), which is the pipe symbol; left and right parentheses "(" and ")", which are used for statement grouping - especially if they are unbalanced, and cap/hat (^), the escape symbol itself.
如果您使用转义技术,您将需要转义这些字符的所有。
如果您使用引号括住相关字符串,则任何正确处理&符号的代码也将处理所有其他符号。
添加百分号 (%) 来指定批处理变量,如果启用了延迟扩展,则添加感叹号 (!),如果您处理的字符串不是 Windows 文件名、文件夹名称或路径,则添加引号。 对于这些字符,引用可能不够,因为批处理脚本解释器在带引号的字符串中搜索以执行替换。您可以通过加倍而不是转义百分号和引号来处理它们(我不确定为什么这会更好或更差)。