batch file deal with Ampersand (&) in folder name

眉间皱痕 提交于 2019-12-03 22:34:40

问题


Batch file below:

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

give the following output:

'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 . . .

Considering I cannot change the folder name, how do I handle the "&"


回答1:


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



回答2:


Unlike Jeb, I don't think you need delayed expansion to use the variable in a safe way. Proper quotation could suffice for most use:

@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

Moreover, this is universal solution while delayed expansion could fail in case of ! exclamation mark in processed string (e.g. last set command above).




回答3:


Here are two ways:

a. Quote the string; e.g:

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

b. Use the escape character; e.g.:

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

To use that path with the cd command, enclose it in quotes.

cd /d "%filelocation%"


来源:https://stackoverflow.com/questions/33351455/batch-file-deal-with-ampersand-in-folder-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!