Bruce Gavin
Bruce Gavin

Reputation: 387

Exclamation (!) Removed from CMD %CD% Output

The Windows CMD shell is stripping the "!" character from directory names.

Assume the current working directory is "C:\\!MyFolder"

Inside a .CMD file I use this syntax:

set _STARTPATH=%CD%
echo %_STARTPATH%

C:\MyFolder is displayed without the bang (!)

This is common from WinXP through Win8.1.

Q: does anybody know a work-around for this?

Upvotes: 1

Views: 201

Answers (2)

Paul
Paul

Reputation: 2710

in delayedexpansion you can try variable search/replace by escaping !:

echo %cd:!=^^!%

But the solution would be to disable delayed expansion momentarily

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

.

@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

Upvotes: 1

jeb
jeb

Reputation: 82307

When you enabled delayed expansion you should use it also for the variable expansion

set _STARTPATH=!CD!
echo !_STARTPATH!

Upvotes: 2

Related Questions