Windows Batch Scripts

Complete Examples

I have some examples of complete scripts at windows/batch · master · Geoff Lawrence / Geoff Does Stuff · GitLab which show a number of things working together.

Hiding Output

On Windows you hide a command's output by redirecting the output to nul, you can separately direct error messages to nul as well. Oh and before you ask, that is just one L. For example:
dir > nul
dir missingfile 2> nul
dir > nul 2> nul
A little experimenting with the above will help. You can also redirect error output (stderr or "2") to normal output (stdout) as follows:
dir > listing.txt 2>&1
However, note that you cannot have space in "2>&1".

Passing Arguments

If you wish to process command line arguments passed to your batch script then you need to examine the variables %1, %2 etc.

Standard Variables

There are a number of standard variables, some less easy/obvious, for example %~dp0! So let's break this down a bit, "%~" is the special key that gets us started, "d" is for driver letter, "p" is for path and 0 (zero) means the script file itself. So, create the following in "C:\Temp\TestScript.cmd"
@ECHO OFF
ECHO Script Path: %~dp0
ECHO Script Short Path: %~dps0
ECHO Script Drive: %~d0
ECHO Script Folder: %~p0
ECHO Script Name: %~nx0
ECHO Script Name and Location: %~dpnx0
This will generate the following output
Script Path: C:\Temp\
Script Short Path: C:\Temp\
Script Drive: C:
Script Folder: \Temp\
Script Name: TestScript.cmd
Script Name and Location: C:\Temp\TestScript.cmd
The "s" means use 8.3 path names, which does not show in this example but move the file to your desktop and try it again, maybe adding a pause command on the end so the windows does not close before you can read it. You can get further information by executing for /? on a command prompt or by reading Microsoft Windows XP - Using batch parameters.

The IF Statement

Sometimes this is a little tricky to get working, so here are a couple of examples:

@ECHO OFF

SET THEDAY=22
SET THEMONTH=11

IF "%THEDAY%"=="21" ECHO "This is the 21st day"

IF "%THEMONTH%"=="12" GOTO December
ECHO Long wait to Christmas
GOTO End

:December
ECHO Christmas Season

:End
ECHO Finished
The basic syntax is this: IF <condition true> <execute statement>

Which is why you will often see the GOTO statement, followed by several more GOTOs and their corresponding labels that are the lines beginning with a colon. You can put the word NOT after the IF to reverse the logic.

Counting Lines

The find command does this quite nicely with /c giving the count and /v looking for non-matching, which is fine as long as nothing does match it! Try the following:
type *.* | find /c /v "~~~~~"
Which worked well for me when I replaced *.* with a specific filename.

Useful Resources

In an ideal world this kind of basic DOS batch scripting would die out in favour of PowerShell, however it continues as a reasonable fall back. So, further help is available: