Batch Syntax Notes

From wiki.adammorgan.org
Jump to: navigation, search

Comparison

  • "AND" Operator
set name=Bob
set age=30
::False statement
IF %name%==Bob IF %age%==20 (
ECHO Name is Bob, AND Age is 20.
)
::True statement
IF %name%==Bob IF %age%==30 (
ECHO Name is Bob, AND Age is 30.
)
  • Comparison Operators[1]
EQU : Equal
NEQ : Not equal
LSS : Less than <
LEQ : Less than or Equal <=
GTR : Greater than >
GEQ : Greater than or equal >=
This 3 digit syntax is necessary because the > and <
symbols are recognised as redirection operators

Findstr

  • Find an entire string (containing spaces) in a file.
    • Findstr will return errorlevel=1 (not found) if the word "Microsoft" is in the file.
    • The entire string (with spaces) must be present for it to return errorlevel=0 (found).
SET _logstring=Microsoft Office Professional Plus 2007
findstr /C:"%_logstring%" C:\MYORG\logs\psinfo_installedappslist.log>NUL
  • Findstr does not support encodings like UCS-2. The workaround is to make a UTF copy of file and then run findstr on it.
TYPE UTF-16.txt > ASCII.txt
FINDSTR object ASCII.txt

Parsing

Script filenames and paths

Script with examples (assuming script file is "\\myfileserver\scripts\temp.bat".

@ECHO OFF
CLS
ECHO Get a script's filename (without extension)
ECHO %~n0
ECHO Get a script's path and name with extension (with quotes)
ECHO %0 
ECHO Get a scripts path and name with extension (no quotes)
ECHO %~0
ECHO Get a script's path (no quote marks, with trailing slash) 
ECHO %~dp0
ECHO Get a scripts path (no quote marks, no trailing slash)
set string=%~dp0
set string=%string:~0,-1%
ECHO %string%
pause

Output:

Get a script's filename (without extension)
temp
Get a script's path and name with extension (with quotes)
"\\myfileserver\scripts\temp.bat"
Get a scripts path and name with extension (no quotes)
\\myfileserver\scripts\temp.bat
Get a script's path (no quote marks, with trailing slash)
\\myfileserver\scripts\
Get a scripts path (no quote marks, no trailing slash)
\\myfileserver\scripts
Press any key to continue . . .

Extracting characters from a string

  • Truncate 3 characters from end of variable
set _freespace=88498577408
set _freespace=%_freespace:~0,-3%
ECHO %_freespace%

Output:

88498577

Output Redirection

REDIRECT Std Output and Std Error to NUL

del c:\thisfileisnotpresent.txt > NUL 2>&1

REDIRECT all command output to a file

(
somecommand.exe /someswitch /anotherswitch
) >> C:\mylog.txt