Prevent batch script from terminating upon invalid character input - windows

I always have this issue when writing batch scripts. Whenever I have the script prompt the user to set a variable, if a semicolon (that's just one example) is inputted, the script will close. Is there a way to prevent it from doing so?
Example:
#echo off
:1
cls
echo Please enter your ID:
set /P id=
if /i %id%==119 goto Tom
if /i %id%==204 goto Brittany
if /i %id%==12 goto Shannon
if /i %id%==64 goto Jack
goto 1
:Tom
cls
echo Tom, you have to mow the lawn.
pause>nul
exit
:Brittany
cls
echo Brittany, you have to fold the laundry.
pause>nul
exit
:Shannon
cls
echo Shannon, you have to feed the dog.
pause>nul
exit
:Jack
cls
echo Jack, you have to replace the radio's capacitors.
pause>nul
exit
What I would see running that script:
C:\>myscript.bat
Please enter your ID:
asjfash;dfjlas;ldf
asjfash;dfjlas;ldf==i was unexpected at this time.
and the script closes.
Thanks!

Read Syntax : Escape Characters, Delimiters and Quotes:
Delimiters
Delimiters separate one parameter from the next - they split the
command line up into words.
Parameters are most often separated by spaces, but any of the
following are also valid delimiters:
Comma (,)
Semicolon (;)
Equals (=)
Space ()
Tab (   )
If a user inputs some string containing any of above listed separators (like set "id=1 19" then %id% contains a space), then
if /i %id%==119 goto Tom
results to
if /i 1 19==119 goto Tom
↑ this space causes error 19==119 was unexpected at this time
Definitely, you need to escape delimiters and all other cmd-poisonous characters as follows:
#echo off
:1
cls
echo Please enter your ID:
set /P id=
if /i "%id%"=="119" goto Tom
if /i "%id%"=="204" goto Brittany
if /i "%id%"=="12" goto Shannon
if /i "%id%"=="64" goto Jack
goto 1
rem script continues here
FYI, Redirection article lists other cmd-poisonous characters which need to be escaped as their unescaped occurrence in a batch script has following meaning:
&  - Single Ampersand: used as a command separator
&& - Double Ampersand: conditional command separator (like if errorlevel 0)
|| - Double Pipe (Vertical Line): conditional command separator (like if errorlevel 1)
|  - Single Pipe: redirects the std.output of one command into the std.input of another
>  - Single Greater Than: redirects output to either a file or file like device
>> - Double Greater than: output will be added to the very end of the file
<  - Less Than: redirect the contents of a file to the std.input of a command

Related

Batch: Slowing processing speed

I am creating a little project to impress my friends, and was curious on how I could slow down the text outflow on the program, using just one line.
I am having a problem (And trust me, I did my research), and was curious as to how to slow down the batch processing speed in general, without doing echo hi TIMEOUT 5>nul echo hi again, etc. But instead, only a single line at the beginning, which slows the output of the text for the whole batch script. Thanks!
The only real way to do this in the batch language would be to use the call command to call a function and to work. This can be placed at the bottom of your batch document.
Furthermore, Since your not real clear on your goal here & from reading the comments, I'm going to assume that from echo hi & TIMEOUT 5>nul echo hi again you want to display each line after 5 seconds BUT from just one line or command. This can be done easily with call & an FOR loop. In this case we can use %* to gather all "Words Line One", "Words Line Two" that you wish.
Combining this with simple syntax-replacement to remove the quotes and we good.
DelayedLine.bat
#echo off
#setlocal EnableDelayedExpansion
Rem | To use the command, Call :SlowOutput "Desired Line" "Desired Line" "Desired Line"
Call :SlowOutput "Line Number One" "Line Number Two" "Line Number Three"
pause>nul
Goto :EOF
:SlowOutput
for %%A in (%*) do (
Set "String=%%A"
Set String=!String:"=%!
echo !String!
Rem | Change 5 To How Many (Seconds) You Wish
Timeout 5 /NoBreak>Nul
)
goto :EOF
If your goal was to have a typewrighter effect, we can use a script by hackoo on this thread here and modify it to work with the call in an organized matter.
This script will display letter by letter and for each call "Word" "Word" new quote a new line. All working by one line via call
LetterDelay.bat
#echo off
Rem | To use the command, Call :SlowText "Desired Text"
Rem | To combine two "echo's" on one line we can use the "&"
Call :SlowText "Hello!" & Call :SlowText "How is your day today?"
pause>nul
Goto :EOF
:SlowText
(
echo strText=wscript.arguments(0^)
echo intTextLen = Len(strText^)
echo intPause = 100
echo For x = 1 to intTextLen
echo strTempText = Mid(strText,x,1^)
echo WScript.StdOut.Write strTempText
echo WScript.Sleep intPause
echo Next
)>%tmp%\%~n0.vbs
#cScript.EXE /noLogo "%tmp%\%~n0.vbs" "%~1"
Rem | echo. is optional. It's used as a constant for a newline \n
echo.
goto :EOF
For help on any of the commands do the following:
call /?
set /?
for /?
if /?
find /?
So on.

Batch file seems to be setting a variable to 2 for no reason

I'm making a simple batch script to figure out arrays in batch script.
The code:
#echo off
setlocal EnableDelayedExpansion
set inputCount=0
set outputCount=0
:input
cls
set /p !number%inputCount%!=Input %inputCount%:
set /a inputCount=%inputCount%+1
if %inputCount% geq 3 goto output
goto input
:output
cls
echo !number%outputCount%!
set /a outputCount=%outputCount%+1
if %outputCount% geq 3 goto exit
goto output
:exit
pause
echo exit
On line 4, I set outputCount to 0, I then don't change outputCount until line 16 where I add 1 to it.
I expected the output of line 16 to be outputCount=0+1=1 therefore making outputCount=1. However, when I run the code with echo on to see exactly what it's doing, the output for line 16 is outputCount=2+1=3 setting outputCount to 3.
It seems that the program is setting outputCount to 2 instead of 0 at some point before line 16 but I can't see why.
First, take a look on Debugging a batch file as this is a lesson you need to learn on coding a batch file.
Second, read the answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? which offers additional information to the help output on running in a command prompt window set /?.
It looks like you want to define the environment variables number0, number1 and number2 with a string assigned to them by user input.
The command to use to prompt a user for a string is either
set /P "variable=prompt text: "
or
set /P variable="prompt text: "
The first variant is in general recommended although most often not used by batch file coding newbies because of not knowing how to use the double quotes right on assigning a string to an environment variable. The second variant is specific for set /P also possible and in some very rare cases really needed, but in my point of view should be avoided to use because of the double quotes are interpreted different on using set without /P.
So let us look on your code with commenting out with rem four lines, appending one more line with set at end of the batch file and run that batch file from within a command prompt window:
rem #echo off
setlocal EnableDelayedExpansion
set inputCount=0
set outputCount=0
:input
rem cls
set /p !number%inputCount%!=Input %inputCount%:
set /a inputCount=%inputCount%+1
if %inputCount% geq 3 goto output
goto input
:output
rem cls
echo !number%outputCount%!
set /a outputCount=%outputCount%+1
if %outputCount% geq 3 goto exit
goto output
:exit
rem pause
echo exit
set number
Output is at end just a line with NUMBER_OF_PROCESSORS=2. There are no environment variables number0, number1, number2 which would be also output by set number. And the command line echo !number%outputCount%! in file results three times in the information that ECHO is OFF.
The reason can be seen on looking on the output command lines really executed after preprocessing each line by Windows command interpreter.
set /p !number%inputCount%!=Input %inputCount%:
The string entered by the user, if not just RETURN or ENTER was hit by the user on prompt, should be assigned to the environment variables of which name are stored in the environment variables number0, number1 and number2. But the environment variables number0, number1 and number2 are never defined by your batch file as your intention is to store the input strings into the variables with name number0, number1 and number2. So this command line is finally on execution:
set /p =Input 0:
set /p =Input 1:
set /p =Input 2:
Those command lines would result in an exit of batch processing because of a syntax error, but this does not occur here because of usage of delayed expansion as it can be seen in the console window.
The solution is a batch code as follows:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
set "Index=0"
:Input
cls
set /A Index+=1
set /P "Number%Index%=Input %Index%: "
if not %Index% == 3 goto Input
cls
set "Index=0"
:Output
set /A Index+=1
if defined Number%Index% echo Number%Index%=!Number%Index%!
if not %Index% == 3 goto Output
endlocal
The output of this batch file on entering on first prompt Hello!, on second prompt nothing and on third prompt Bye! is:
Number1=Hello!
Number3=Bye!
Okay, we have not entered a number as we have the freedom to type anything from nothing to bad strings like Double quote " or | or < or > are bad inputs on user prompt on being prompted for an input. But the batch file works as expected now.
Further please note that the string after set /A is an arithmetic expression which is parsed completely different to any other string on a command line. For examples the current values of environment variables can be referenced by using just the variable name without surrounding percent signs or exclamation marks. That make it possible to use variables in arithmetic expression within an IF or FOR command block without usage of delayed expansion. The help output on running set /? in a command prompt window explains this different parsing behavior quite good as well as which operators can be used like += in the arithmetic expression.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cls /?
echo /?
endlocal /?
goto /?
if /?
rem /?
set /?
setlocal /?
Some more hints:
Don't use just exit in a batch file, use exit /B or goto :EOF, see Where does GOTO :EOF return to?
After verification that the user entered anything at all and the entered string is really a number (decimal, octal or hexadecimal), make sure to process the number right according to your and the users' expectations. What I mean here is demonstrated with:
#echo off
set "Number=020"
set /A Number+=1
echo Result=%Number%
pause
What do you expect as result, 21 or the real output result 17?
A number string starting with 0 is interpreted as octal number. A number string starting with 0x or 0X is interpreted as hexadecimal number. Change 020 to 008 and the result is 1. Why? 008 is invalid for an octal number and therefore replaced by 0 which is incremented by one.

Verify 'X' number of digits have been inputted in batch script

Writing a batch script. How can I verify '3' NUMERIC digits have been inputted by a user with the "/p" prompt?
Prompt to user:
SET /P SITEID=ENTER SITE # (i.e. 001 - MUST BE 3 DIGITS):
I need to verify 3 digits have been inputted, if good continue with script. If NOT good re-prompt user to message of my choosing.
#echo off
setlocal
set "Input="
:Prompt
set /p "Input=ENTER SITE # (i.e. 001 - MUST BE 3 DIGITS): "
if not defined Input goto Prompt
set "Input=%Input:"=%"
for /f "delims=0123456789" %%A in ("%Input%") do goto Prompt
for /f "tokens=1* delims=0" %%A in ("10%Input%") do set "Input=%%B"
if %Input%0 geq 10000 goto Prompt
set "Input=000%Input%"
set "Input=%Input:~-3%"
echo Success = %Input%
pause
endlocal
exit /b 0
Script Explanation:
Prompt for Input
Validate Input
Remove Poison Quotation Characters
Verify Input is only Numbers
Remove leading 0's for comparison
Verify Input is less than 1000
Add back leading 0's
Display Success
If any validation fails, the user is prompted again
Update:
Fix leading 0 removal
Add example of how to add back leading 0's
:loop
SET /P "SITEID=ENTER SITE # (i.e. 001 - MUST BE 3 DIGITS):"
echo("%SITEID:"= %"|findstr /rbe /c:"""[0-9][0-9][0-9]""" >nul || ( echo FAIL & goto loop )
It takes the %SITEID% variable, removes quotes if present and send the data into findstr to test against a regular expression (/r switch) : at the begining of data (/b switch) initial quote (from the echo command) three numeric characters, a closing quote (from the echo command) and end of string (/e switch). If the findstr does not found a match, errorlevel is set and the code after || is executed, printing a message to console an returning to the :loop label to ask again.

Windows equivalent of "echo -n" no longer works in Win7

I had a nifty trick in Windows cmd.exe (at least up to XP) to emulate the behaviour of the UNIX echo without a newline, echo -n. For example, the command:
<nul: set /p junk= xyzzy
would result in exactly six characters being output, the leading space and the string "xyzzy", and nothing else.
If you're interested in why this works, it's actually an input command which outputs " xyzzy" as the prompt then waits for user input before assigning that input to the junk environment variable. In this particular case, it doesn't wait for user input since it grabs the input from the nul device.
It was rather useful in cmd scripts when (for example) processing files in a loop (one iteration per file) where you want to list more than one per line. By using this trick, you could simply output each file name followed by a space and no newline then, after the loop, output a newline to finish up:
Processing files:
file1.txt file42.txt p0rn.zip
Now I discover that, under Windows 7, the spaces are no longer output so what I get is:
Processing files:
file1.txtfile42.txtp0rn.zip
Is there a way I can get set /p to start honouring my spaces again, or is there another way in Win7 to achieve the same effect?
I've tried quoting, using . (which works in echo) and even escaping the string with ^, but none of them seem to work:
C:\Pax> <nul: set /p junk= xyzzy
xyzzy
C:\Pax> <nul: set /p junk=" xyzzy"
xyzzy
C:\Pax> <nul: set /p junk=' xyzzy'
' xyzzy'
C:\Pax> <nul: set /p junk=. xyzzy
. xyzzy
C:\Pax> <nul: set /p junk=^ xyzzy
xyzzy
What I need is:
C:\Pax> some_magical_command_with_an_argument xyzzy
xyzzy
which will give me the space(s) at the start and no newline at the end.
This is very similar to paxdiablo's answer, except I use a hybrid JScript/batch file instead of a temporary VBScript file.
My script is called jEval.bat - and it simply evaluates any valid JScript expression and writes the result to stdout, optionally with a trailing newline. The silly little script is extremely useful for batch programming.
Assuming jEval.bat is either in your current folder, or somewhere in your PATH, then you can simply do something like:
call jeval "' xyzzy'"
Here is the script. It really is very simple. Most of the code is related to documentation, error handling, and a built in help system.
#if (#X)==(#Y) #end /* harmless hybrid line that begins a JScrpt comment
::************ Documentation ***********
:::
:::jEval JScriptExpression [/N]
:::jEval /?
:::
::: Evaluates a JScript expression and writes the result to stdout.
:::
::: A newline (CR/LF) is not appended to the result unless the /N
::: option is used.
:::
::: The JScript expression should be enclosed in double quotes.
:::
::: JScript string literals within the expression should be enclosed
::: in single quotes.
:::
::: Example:
:::
::: call jEval "'5/4 = ' + 5/4"
:::
::: Output:
:::
::: 5/4 = 1.25
:::
::************ Batch portion ***********
#echo off
if "%~1" equ "" (
call :err "Insufficient arguments"
exit /b
)
if "%~2" neq "" if /i "%~2" neq "/N" (
call :err "Invalid option"
exit /b
)
if "%~1" equ "/?" (
setlocal enableDelayedExpansion
for /f "delims=" %%A in ('findstr "^:::" "%~f0"') do (
set "ln=%%A"
echo(!ln:~3!
)
exit /b
)
cscript //E:JScript //nologo "%~f0" %*
exit /b
:err
>&2 echo ERROR: %~1. Use jeval /? to get help.
exit /b 1
************ JScript portion ***********/
if (WScript.Arguments.Named.Exists("n")) {
WScript.StdOut.WriteLine(eval(WScript.Arguments.Unnamed(0)));
} else {
WScript.StdOut.Write(eval(WScript.Arguments.Unnamed(0)));
}
This isn't using set or other cmd-internal stuff, but you can use cscript (also included in a standard Windows install) to do a similar thing. You can even control it from the cmd file itself (no separate files to maintain) by use of creating temporary vbs files.
Place this code in your cmd file:
rem Create the VBS file to output spaces and a word.
echo.for i = 1 to WScript.Arguments.Item(0) >spacetext.vbs
echo. WScript.StdOut.Write ^" ^" >>spacetext.vbs
echo.next >>spacetext.vbs
echo.WScript.StdOut.Write WScript.Arguments.Item(1) >>spacetext.vbs
rem Do this once per word you want output (eg, in a loop).
cscript /nologo spacetext.vbs 0 Hello,
cscript /nologo spacetext.vbs 1 my
cscript /nologo spacetext.vbs 1 name
cscript /nologo spacetext.vbs 1 is
cscript /nologo spacetext.vbs 4 Pax.
rem Do this at the end to add newline and kill temp file.
echo.
del spacetext.vbs
The output of this is what you would expect:
Hello, my name is Pax.
You mean like this?
#ECHO OFF
SETLOCAL
FOR /l %%i IN (1,1,4) DO <NUL SET /p var="item %%i "
Result:
item 1 item 2 item 3 item 4
Or do you absolutely insist on a space at the start?
OK, have the right answer now: you can't have a leading <space> in Win7 with set /p. There are differences between Windows versions:
Syntax | XP | Vista and Windows 7
----------------------+-------------------------------------+-------------------------------------
<nul set /p =!msg! |- If 1st char is quote, then trims |- Trims leading white space chars.
or | that quote, and if at least one |- If 1st non white space char is
<nul set /p "=!msg!" | additional quote, than trims last | quote, then that quote is treated
| quote and all remaining chars. | as white space and trimmed, and if
|- If 1st non trimmed char is =, then | at least one additional quote, then
| syntax error. | trims last quote and all remaining
| | chars.
| |- If 1st non trimmed char is =, then
| | syntax error.
----------------------+-------------------------------------+-------------------------------------
<nul set /p ="!msg!" |- Trims leading control chars and |- Trims leading white space chars.
or | spaces. |- If 1st non trimmed char is =, then
<nul set /p "="!msg!""|- If 1st non trimmed char is =, then | syntax error.
| syntax error. |
----------------------+-------------------------------------+-------------------------------------
On Vista and Windows 7, the trimmed leading white space chars are:
9 0x09 Horizontal Tab
10 0x0A New Line
11 0x0B Vertical Tab
12 0x0C Form Feed
13 0x0D Carriage Return
32 0x20 Space
255 0xFF Non-breaking Space
source
For an other technique to get leading spaces in pure batch see here

Hidden features of Windows batch files

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
What are some of the lesser know, but important and useful features of Windows batch files?
Guidelines:
One feature per answer
Give both a short description of the feature and an example, not just a link to documentation
Limit answers to native funtionality, i.e., does not require additional software, like the Windows Resource Kit
Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.
(See also: Windows batch files: .bat vs .cmd?)
Line continuation:
call C:\WINDOWS\system32\ntbackup.exe ^
backup ^
/V:yes ^
/R:no ^
/RS:no ^
/HC:off ^
/M normal ^
/L:s ^
#daily.bks ^
/F daily.bkf
PUSHD path
Takes you to the directory specified by path.
POPD
Takes you back to the directory you "pushed" from.
Not sure how useful this would be in a batch file, but it's a very convenient command to use in the command prompt:
C:\some_directory> start .
This will open up Windows Explorer in the "some_directory" folder.
I have found this a great time-saver.
I have always found it difficult to read comments that are marked by a keyword on each line:
REM blah blah blah
Easier to read:
:: blah blah blah
Variable substrings:
> set str=0123456789
> echo %str:~0,5%
01234
> echo %str:~-5,5%
56789
> echo %str:~3,-3%
3456
The FOR command! While I hate writing batch files, I'm thankful for it.
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do #echo %i %j %k
would parse each line in myfile.txt, ignoring lines that begin with a semicolon, passing the 2nd and 3rd token from each line to the for body, with tokens delimited by commas and/or spaces.
Notice the for body statements reference %i to get the 2nd token, %j to get the 3rd token, and %k to get all remaining tokens after the 3rd.
You can also use this to iterate over directories, directory contents, etc...
Rather than litter a script with REM or :: lines, I do the following at the top of each script:
#echo OFF
goto :START
Description of the script.
Usage:
myscript -parm1|parm2 > result.txt
:START
Note how you can use the pipe and redirection characters without escaping them.
The path (with drive) where the script is : ~dp0
set BAT_HOME=%~dp0
echo %BAT_HOME%
cd %BAT_HOME%
The %~dp0 piece was mentioned already, but there is actually more to it:
the character(s) after the ~ define the information that is extracted.
No letter result in the return of the patch file name
d - returns the drive letter
p - returns the path
s - returns the short path
x - returns the file extension
So if you execute the script test.bat below from the c:\Temp\long dir name\ folder,
#echo off
echo %0
echo %~d0
echo %~p0
echo %~dp0
echo %~x0
echo %~s0
echo %~sp0
you get the following output
test
c:
\Temp\long dir name\
c:\Temp\long dir name\
.bat
c:\Temp\LONGDI~1\test.bat
\Temp\LONGDI~1\
And if a parameter is passed into your script as in
test c:\temp\mysrc\test.cpp
the same manipulations can be done with the %1 variable.
But the result of the expansion of %0 depends on the location!
At the "top level" of the batch it expands to the current batch filename.
In a function (call), it expands to the function name.
#echo off
echo %0
call :test
goto :eof
:test
echo %0
echo %~0
echo %~n0
The output is (the batchfile is started with myBatch.bat )
myBatch.bat
:test
:test
myBatch
By using CALL, EXIT /B, SETLOCAL & ENDLOCAL you can implement subroutines with local variables.
example:
#echo off
set x=xxxxx
call :sub 10
echo %x%
exit /b
:sub
setlocal
set /a x=%1 + 1
echo %x%
endlocal
exit /b
This will print
11
xxxxx
even though :sub modifies x.
Sneaky trick to wait N seconds (not part of cmd.exe but isn't extra software since it comes with Windows), see the ping line. You need N+1 pings since the first ping goes out without a delay.
echo %time%
call :waitfor 5
echo %time%
goto :eof
:waitfor
setlocal
set /a "t = %1 + 1"
>nul ping 127.0.0.1 -n %t%
endlocal
goto :eof
Escaping the "plumbing":
echo ^| ^< ^> ^& ^\ ^^
Being able to run commands and process the output (like backticks of '$()' in bash).
for /f %i in ('dir /on /b *.jpg') do echo --^> %i
If there are spaces in filenames, use this:
for /f "tokens=*" %i in ('dir /on /b *.jpg') do echo --^> %i
Creating an empty file:
> copy nul filename.ext
To hide all output from a command redirect to >nul 2>&1.
For example, the some command line programs display output even if you redirect to >nul. But, if you redirect the output like the line below, all the output will be suppressed.
PSKILL NOTEPAD >nul 2>&1
EDIT: See Ignoring the output of a command for an explanation of how this works.
PAUSE
Stops execution and displays the following prompt:
Press any key to continue . . .
Useful if you want to run a batch by double-clicking it in Windows Explorer and want to actually see the output rather than just a flash of the command window.
The equivalent of the bash (and other shells)
echo -n Hello # or
echo Hello\\c
which outputs "Hello" without a trailing newline. A cmd hack to do this:
<nul set /p any-variable-name=Hello
set /p is a way to prompt the user for input. It emits the given string and then waits, (on the same line, i.e., no CRLF), for the user to type a response.
<nul simply pipes an empty response to the set /p command, so the net result is the emitted prompt string. (The variable used remains unchanged due to the empty reponse.)
Problems are: It's not possible to output a leading equal sign, and on Vista leading whitespace characters are removed, but not on XP.
Search and replace when setting environment variables:
> #set fname=%date:/=%
...removes the "/" from a date for use in timestamped file names.
and substrings too...
> #set dayofweek=%fname:~0,3%
Integer arithmetic:
> SET /A result=10/3 + 1
4
Command separators:
cls & dir
copy a b && echo Success
copy a b || echo Failure
At the 2nd line, the command after && only runs if the first command is successful.
At the 3rd line, the command after || only runs if the first command failed.
Output a blank line:
echo.
You can chain if statements to get an effect like a short-circuiting boolean `and'.
if foo if bar baz
To quickly convert an Unicode text file (16bit/char) to a ASCII DOS file (8bit/char).
C:\> type unicodeencoded.txt > dosencoded.txt
as a bonus, if possible, characters are correctly mapped.
if block structure:
if "%VS90COMNTOOLS%"=="" (
echo: Visual Studio 2008 is not installed
exit /b
)
Delayed expansion of variables (with substrings thrown in for good measure):
#echo off
setlocal enableextensions enabledelayedexpansion
set full=/u01/users/pax
:loop1
if not "!full:~-1!" == "/" (
set full2=!full:~-1!!full2!
set full=!full:~,-1!
goto :loop1
)
echo !full!
endlocal
Doesn't provide much functionality, but you can use the title command for a couple of uses, like providing status on a long script in the task bar, or just to enhance user feedback.
#title Searching for ...
:: processing search
#title preparing search results
:: data processing
Don't have an editor handy and need to create a batch file?
copy con test.bat
Just type away the commands, press enter for a new line.
Press Ctrl-Z and Enter to close the file.
example of string subtraction on date and time to get file named "YYYY-MM-DD HH:MM:SS.txt"
echo test > "%date:~0,4%-%date:~5,2%-%date:~8,2% %time:~0,2%_%time:~3,2%_%time:~6,2%.txt"
I use color to indicate if my script end up successfully, failed, or need some input by changing color of text and background. It really helps when you have some machine in reach of your view but quite far away
color XY
where X and Y is hex value from 0 to F, where X - background, Y - text, when X = Y color will not change.
color Z
changes text color to 'Z' and sets black background, 'color 0' won't work
for names of colors call
color ?
Total control over output with spacing and escape characters.:
echo. ^<resourceDir^>/%basedir%/resources^</resourceDir^>
TheSoftwareJedi already mentioned the for command, but I'm going to mention it again as it is very powerful.
The following outputs the current date in the format YYYYMMDD, I use this when generating directories for backups.
for /f "tokens=2-4 delims=/- " %a in ('DATE/T') do echo %c%b%a

Resources