2

I'm working on a script where I have the following code:

:top  
Echo Enter Message
set /p msg=">"
if "%msg%"=="C" goto cancel
echo %msg% >> File.txt
goto top
:cancel

I'm looking for a way for the set /p to accept &^*<>?| and all that stuff and still echo it into the File. Is this possible? Currently the script just crahses

1 Answer 1

1

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
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .