批处理文件处理文件夹名称中的Ampersand(&)

时间:2015-10-26 17:03:15

标签: batch-file directory ampersand

下面的批处理文件:

|

给出以下输出:

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

考虑到我无法更改文件夹名称,我该如何处理“&”

3 个答案:

答案 0 :(得分:5)

您需要进行两项更改。

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 ^!"

答案 1 :(得分:0)

以下是两种方式:

一个。引用字符串; e.g:

set "filelocation=C:\Users\myself\Documents\This&That"

湾使用转义字符; e.g:

set filelocation=C:\Users\myself\Documents\This^&That

要将该路径与cd命令一起使用,请将其括在引号中。

cd /d "%filelocation%"

答案 2 :(得分:0)

Jeb不同,我认为您不需要delayed expansion以安全的方式使用变量。适当的报价可以满足大多数用途:

@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命令),则延迟扩展可能会失败。