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

Buc*_*son 2 directory batch-file ampersand

批量文件如下:

@echo off
set filelocation=C:\Users\myself\Documents\This&That
cd %filelocation%
echo %filelocation%
pause
Run Code Online (Sandbox Code Playgroud)

给出以下输出:

'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 . . .
Run Code Online (Sandbox Code Playgroud)

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

jeb*_*jeb 5

您需要进行两项更改.

1)带引号的扩展集语法在变量名前缀和内容的末尾

2)延迟扩展以安全的方式使用变量

setlocal enableDelayedExpansion
set "filelocation=C:\Users\myself\Documents\This&That"
cd !filelocation!
echo !filelocation!
Run Code Online (Sandbox Code Playgroud)

延迟扩展的工作方式就像扩展百分比一样,但必须首先启用它setlocal EnableDelayedExpansion,然后变量可以用感叹号扩展,!variable!并且仍然具有百分比%variable%.

变量延迟扩展的优点是扩展始终是安全的.
但是,与扩展百分比一样,当您需要它作为内容时,您需要加倍百分比,当您将其用作内容时,您必须使用插入符号来转义感叹号.

set "var1=This is a percent %%"
set "var2=This is a percent ^!"
Run Code Online (Sandbox Code Playgroud)

  • @Bill_Stewart Powershell只是今天的另一个微软工具_未来_而且明天MS将推出下一个工具_the future_然后PowerShell与所有其他MS工具/技术一样被弃用.MS从未在10年或20年内建立任何可靠的东西,这样的东西只存在于Linux世界中 (2认同)