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.
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".
If you wish to process command line arguments passed to your batch script then you need to examine the variables %1, %2 etc.
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
This will generate the following output
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
Script Path: C:\Temp\
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
Script Short Path: C:\Temp\
Script Drive: C:
Script Folder: \Temp\
Script Name: TestScript.cmd
Script Name and Location: C:\Temp\TestScript.cmdpause
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.
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 FinishedThe 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.
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.
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: