Windows Batch Files

Useful variables

  • %0 - the command used to call the batch file (could be foo, ..\foo, c:\bats\foo, etc.)
  • %1 is the first command line parameter,
  • %2 is the second command line parameter,
    • and so on till %9 (and SHIFT can be used for those after the 9th).
  • %~nx0 - the actual name of the batch file, regardless of calling method (some-batch.bat)
  • %~dp0 - drive and path to the script (d:\scripts)
  • %~dpnx0 - is the fully qualified path name of the script (d:\scripts\some-batch.bat)
  • %cmdcmdline% - exact command line used to start the current Cmd.exe
    • When launched from a command console, this var is "%SystemRoot%\system32.cmd.exe"
    • When launched from explorer this var is cmd /c ""[d:\path\script.bat]" "

Useful Websites


Yes, you can do functions in batch files. I have another page where I put batch file functions. Windows Batch File Functions

Replace Chars in Strings

::Replace the character string 'NY' with 'WA'
SET test=I love NY
SET result=%test:NY=WA%
ECHO %result%          =I love WA

Remove Char from string

SET _no_spaces=%_some_var: =% 
SET _no_quotes=%_some_var:"=%   

Test if string has more than or less than X Chars

If all you need is to know if there are two or less characters in a variable you can see if a substring expands to nothing:

if not defined var (
  echo Var is empty!
) else if "%var:~2%"=="" (
  echo var contains 2 or less characters
) else echo var contain more than 2 characters


Specify an offset and a length. You can also specify a negative offset

Postive Offset -- Outputs oob

Positive offset starts at the front of the string

set foo=foobar
echo %foo:~1,3%

Negative Offset -- Outputs oba

Negative offset, let's you start at the back of the string

set foo=foobar
echo %foo:~-4,3%

Determine if batch files was run from Command Console or Windows Explorer

At top of your program, add this code...

:: See if program was run from console (command line) or explorer (double click or windows shortcut)
set run_from=console
IF "%cmdcmdline:~0,3%"=="cmd" set run_from=explorer 

Later on, you can make decisions based on this...

:: if they ran from explorer, we need to pause to keep from closing the window
if %run_from%==explorer pause


Make sure you do it exactly as shown

IF statement (
) ELSE (

Case Insensitive compare

:: Case Insenstive Compare
if /I %param% EQU %CompareValue% (