感叹号(!)已从CMD%CD%输出

时间:2015-10-03 13:28:14

标签: windows batch-file cmd escaping delayedvariableexpansion

Windows CMD shell正在剥离" !"目录名称中的字符。

假设当前工作目录为" C:\\!MyFolder"

在.CMD文件中我使用以下语法:

set _STARTPATH=%CD%
echo %_STARTPATH%
显示

C:\MyFolder时没有爆炸(!

这在WinXP到Win8.1中很常见。

问:有人知道解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

启用延迟扩展后,您还应将其用于变量扩展

set _STARTPATH=!CD!
echo !_STARTPATH!

答案 1 :(得分:1)

!

您可以variable search/replace echo %cd:!=^^!% 尝试escaping

...
setlocal disabledelayedexpansion
echo %cd%
setlocal enabledelayedexpansion
...

但解决方案是暂时disable delayed expansion

@echo off
setlocal
rd !MyFolder
md !MyFolder
setlocal enabledelayedexpansion
echo enabledelayedexpansion is ON
@timeout /t 1 /nobreak>nul
echo dir /b /ad "^!*"
echo.
dir /b /ad "^!*"

@timeout /t 1 /nobreak>nul
echo.
echo cd ^^^^^^^^^^^!Myfolder 7 more caret to show double caret ecaping ^^! in echo - 13 carets used in that line.
echo cd ^^!Myfolder double caret to escape ^^!
echo cd "^!Myfolder" single caret inside double quotes to escape ^^!
cd ^^!Myfolder

@timeout /t 1 /nobreak>nul
echo.
echo ^^^!cd^^^!: !cd!
echo %%cd%%: %cd:!=^^!%

@timeout /t 1 /nobreak>nul

endlocal

echo.
echo %%cd%% and  ^!cd^! after endlocal:
@timeout /t 1 /nobreak>nul
echo %cd%
echo !cd!

exit /b 0

departure_address