Use command line switches in a bat file

This explains how to use command line switches within a bat file.

For example, you may want to add a switch to your file that runs only a specific section of your bat file. Such as adding a /r switch

c:\mybat.bat /r

You target the /r within your bat file using the %1 variable. So, within the below bat file we tell it that %1 = /r
Then using an IF statement, we can tell the bat exactly what to do if our bat file is run with the /r switch.

echo off
if "%1"=="/r" goto switch
echo no switch was used to launch me!
pause

:switch
echo I was launched using the /r switch!
pause

Go ahead, try it, save the following into notepad and save it as switch.bat
When you run it from the command prompt with and without the /r switch you will see the difference.

You can of course then use the same technique to get other information from the command line.
For example, you may want to type in a directory location to perform backups etc and use that within the bat file.
The method is exactly the same as above except that we will now be using two variables, %1 and %2

c:\switch.bat /r d:\backup\myfiles

within your bat file you could define the switches as follows

echo off
if "%1"=="/r" goto switch
echo no switch was used to launch me!
pause

:switch
SET data=%2
echo I was launched using the /r switch and a data path as well!
echo the backup directory will now be set as %data%
echo and can be called anywhere in my bat file by typing %data%
pause

It is easy to add up to 9 switches / variables the same way, any more than that requires the use of another command called SHIFT, which we will talk about in a different guide.

Print Friendly, PDF & Email

More Like This


Categories


Win 7 / 10 Tips & Tricks Windows XP Tips & Tricks

Tags


  • Post a comment