Method 1: Delayed Expansion
One way to do what you want is to use Delayed Expansion which leaves special characters alone.
Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command.
:top
Echo Enter Message
set /p msg=">"
if "%msg%"=="C" goto cancel
setlocal EnableDelayedExpansion
echo !msg! >> File.txt
endlocal
goto top
:cancel
As you can see, you will need to use !msg!
instead of %msg%
.
Method 2: Quotes
Putting quotes around the variable also leaves special characters alone, with the side-effect of having those quotes pass into your output as well.
:top
Echo Enter Message
set /p msg=">"
if "%msg%"=="C" goto cancel
echo "%msg%" >> File.txt
goto top
:cancel