Pinterest Stumbleupon Whatsapp
Ads by Google

It’s the mundane that makes the day drag on. Simple, repetitive tasks that sap your life force. We either do them begrudgingly, or we neglect them until they create an even larger problem. It doesn’t have to be that way!

With Windows computers, you can create simple little programs, called batch files, that will take care of these tiresome tasks.

dos commands in command window

That’s the point of automation, isn’t it? To set it and forget it, as the infomercials say. Let’s take a look at the parts of a batch file and how to create some cantrips for your chores.

What’s a Batch File?

Back before Windows, everything was accomplished by typing commands instead of pointing and clicking. The Microsoft version is known as MS-DOS (Microsoft Disk Operating System) and the commands are known as DOS commands A Beginners Guide To The Windows Command Line A Beginners Guide To The Windows Command Line Read More .

Sometimes, there were tasks where all you needed to do was enter commands in the same order, every time. You could create a file of these commands and name it something like BORING_TASKS.BAT. Then, by simply typing BORING_TASKS.BAT and pressing the Enter key, that list of commands would be executed.

Ads by Google


As Windows came on the scene, Microsoft was still depending on these batch files to do things in the background. They had to leave the capability to run these files. That maintained the ability for people to create and run their own batch files.

Batch files often became the go to tools for power users and system administrators The Windows Command Prompt: Simpler And More Useful Than You Think The Windows Command Prompt: Simpler And More Useful Than You Think The commands haven't always stayed the same, in fact some have been trashed while other newer commands came along, even with Windows 7 in fact. So, why would anyone want to bother clicking the start... Read More alike. There’s no reason why you can’t use batch files, too! Let’s look at a few things you could do.

How to Create a Batch File

All you need is Notepad, a cheat sheet of batch commands, and a little time and patience. Open up Notepad, write the commands you want, then save the file, but change the Save as type: field to All Files, and change the file extension to .bat. That’s really important. Now you’ll have a batch file that you can use as you see fit.


If you need to make changes to the batch file, right-click on it and choose Edit. This will open it up in Notepad and you can edit it again. Simple.

To master the basics, go through our How To Write A Simple Batch File How to Write a Simple Batch (BAT) File How to Write a Simple Batch (BAT) File Batch files can automate everyday computer tasks. We'll show you how batch files work and teach you the basics. By the end of this article, you'll have written your first batch file. Read More  article. Let’s look at a few tasks we could handle with batch files.

Limit Computer Time with a Batch File

Windows Family Safety Internet Safety For Your Kids: Enable Parental Control On Windows 8 Internet Safety For Your Kids: Enable Parental Control On Windows 8 The Internet opens great possibilities and countless risks, especially for children. Windows 8 has a built-in parental control called Family Safety. It enables the system administrator to monitor the activity of other users. Read More has been around since Windows 7 and can handle the job of limiting computer 4 Ways to Manage Your Kids' Internet Use With Your Router 4 Ways to Manage Your Kids' Internet Use With Your Router How do you make sure that your kids are actually up in their room sleeping on a school night, and not staying up all night streaming Internet videos? Read More time quite nicely. But maybe you want to set up the computer so that no matter who logs on, they’ll only get a certain amount of time on the computer before it shuts down. Or maybe you want to use your computer to stream radio, but shut down after a while in case you leave or fall asleep. There’s a batch file for that!

@echo off
shutdown -s -t 3600

@echo off – Tells the computer to not show anything that comes after it in the command window when the batch file runs.

shutdown – This command is obvious, but the parameters -s and -t aren’t necessarily as obvious. -s tells the computer to really shut down, not to just log off (-l) or reboot (-r). The -t parameter is what tells the computer to use a timer.

Once the batch file is initiated, the computer will start counting the seconds. For this example, the timer runs for an hour, which is 3600 seconds. When the time hits 3600 seconds, the computer will shut down. You can change that number to anything you want.

computer time limit

If you want to limit how long a computer runs after someone logs in, save your shutdown.bat file to the Startup directory. In Windows 7 and earlier it will be located at C:\Documents and Settings\All Users\Start Menu\Programs\Startup. In Windows 8, and 8.1, it’s located at C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp.

Now when a person logs in, that batch file will automatically run and the timer starts timing. With some tweaking in a Windows Script with VBScript Better Than Batch: A Windows Scripting Host Tutorial Better Than Batch: A Windows Scripting Host Tutorial Read More this could also be a good April Fools’ Day prank Four Funny Ways To Prank Your Parents With The Family Computer Four Funny Ways To Prank Your Parents With The Family Computer Read More .

Delete All the Files in a Folder

If you have a program that creates lots of log files in a specific directory, it can be time-consuming and annoying to try to delete them all the old fashioned way. Let’s create a batch file that deletes all the files in a folder, without you even having to think about it. The code below is very simple and only empties one specific folder.

cd C:\Folder\Subfolder
del /f/q *

cd – Tells your computer to change directory to the location you’ve specified. In this example it’s C:\Folder\Subfolder. It will delete ALL files inside of that folder. Change that to whatever you wish, but make sure it’s really the directory you want to empty, for example a download folder.

del – This means delete. The /f parameter forces the deletion of read-only files and the /q parameter tells the computer to do it quietly. That means that the names of all the files you’re deleting won’t print out in the command window. The asterisk (*) tells the computer to delete ALL files. The asterisk is a wildcard character.

delete files with batch file

You can get more precise with what you want to delete. Let’s say that you only want to delete all the plain text files in a directory, because those are the logs that are taking up space. Instead of having the asterisk at the end of your del command, you could use *.txt. That tells it to delete any file with the file extension of .txt. Now, only those files will get deleted from that directory.

cd C:\Folder\SubfolderOne
del /f/q *.txt

Let’s say there’s lots of text files in there, and all your log files begin with log-dd-mm-yy. Simply use the asterisk between log and .txt, so it will look like log*.txt. That will delete any file whose name begins with log and has the file extension of .txt.

cd C:\Folder\SubfolderTwo
del /f/q log*.txt

Clear out multiple folders? Simple. Add another section that is the same, but have your cd command point to the other folder. Then your batch file looks something like:

cd C:\Folder\SubfolderOne
del /f/q log*.txt

cd C:\Folder\SubfolderTwo
del /f/q log*.txt

Play with this batch file and you’ll find many creative ways to use it. You can have it as a batch file that you manually run, or you can use Windows Task Scheduler Run Programs Automatically Using Windows Task Scheduler Run Programs Automatically Using Windows Task Scheduler Read More to make it run at a set time every so often. You could even have it run on startup as a lightweight alternative to CCleaner Cleaners Compared: CCleaner vs. Slimcleaner vs. IObit Advanced SystemCare Cleaners Compared: CCleaner vs. Slimcleaner vs. IObit Advanced SystemCare Although Windows is a very capable operating system, it is infamous for its deteriorating performance over time. With the help of some clever system cleaners, however, you can drastically increase the life expectancy of your... Read More .

Choose a Random Number

Here’s a nice little batch file that will generate a random 4-digit number. Why would you want to do that? Lots of things require 4-digit pass codes, like the PIN for your bank card for example. Maybe you manage users in a business and your access control system uses a 4-digit number. Many of them do. If you just try to pull one out of your head, you’ll eventually find yourself creating pass codes that are anything but random. This batch file will take care of that.

@echo off
set /a ran=%random%
if /i %ran% GTR 9999 goto :start
if /i %ran% LSS 1000 goto :start
echo Batch chose the number %ran%

:start – Creates a label named start, that acts like a rally point. Anytime a goto command points to it, the computer will go back to that point in the script and do whatever it says on the line after that label.

set /a – Tells the computer that there’s going to be a new variable that’s a number, the /a parameter tells it to round down to the nearest whole number. So if the value was 1234.6, it would get rounded off to just 1234.

The name of the variable is ran. You could call it whatever you want, but ran makes some sense for a random number.

%random% – This is a dynamic variable, meaning each time the computer comes across it, it’s going to assign it a new value. The %random% dynamic variable will generate a number from 0 to 32767.

We want a 4-digit number so it has to be between 1000 and 9999. That’s what the next 2 lines are for.

if – It’s the beginning of a conditional statement – IF this condition is true THEN do something. The first line is saying if the integer in the variable ran is greater than (GTR) 9999, go to the start and try again. If the value of ran is lower than (LSS) 9999, the computer will continue to the next line. The second line is saying if the value of ran is less than 1000, go to the start and try again. There are several different operators we can use to compare numbers in a batch file.

lottery balls and numbers from Lost

You might be thinking that 0001 is a 4-digit number, and you’d be right. Only, the %random% dynamic variable won’t generate that. It could generate the single digit of 1, but it won’t put the 3 leading zeroes on it. That limits us to just 8999 4-digit numbers. Surely that’s enough for our purposes.

Eventually, the computer will put out a number that falls between 1000 and 9999. Let’s say it picked 4428. At that point, the batch file will use the echo command to display the sentence, “Batch chose the number 4428”. You’ve got your 4-digit random number, now. This process goes a lot faster than trying to explain it–well, less than a second.

pause – It holds the command window open until you press a key. That gives you time to write down your random number.

Rename Several Files with a Batch File

Files downloaded with BitTorrent 8 Legal Uses For BitTorrent: You'd Be Surprised 8 Legal Uses For BitTorrent: You'd Be Surprised Like HTTP, which your browser uses to communicate with websites, BitTorrent is just a protocol. You could use your browser to download pirated content, just as you could use a BitTorrent client to download pirated... Read More often have a lot of excess letters in their names. There’s nothing wrong with that, yet it would look nice if you could remove all that extra stuff. Let’s say you’ve downloaded public domain eBooks Search Or Browse One Million Public Domain Legal Torrents In The Internet Archive Search Or Browse One Million Public Domain Legal Torrents In The Internet Archive Browse and download over one million public domain movies, audiobooks and live concerts using BitTorrent. It's all thanks to The Internet Archive, who you might know as the organization behind the Wayback Machine. They've started... Read More and the file names all look like BookName.UploaderGuy.PD.epub, where BookName is the name of the book. You can use this batch file to strip that .UploaderGuy.PD out of the file name.

@echo off
SET old=.UploaderGuy.PD
SET new=
for /f "tokens=*" %%f in ('dir /b *.epub') do (
SET newname=%%f
SET newname=!newname:%old%=%new%!
move "%%f" "!newname!")

There’s a lot going on here. Some of it will make sense based on what we’ve learned so far. This is a good point to send you off on your own to expand on what we’ve covered and to start teaching yourself more about the power of a well crafted batch file. Let’s call it independent study time.

End of File

We’ve covered what a batch file is, the basics of creating one, and a few examples of useful ones. We’ve shown you where to find more information about creating and using batch files. Hopefully, we’ve also had some fun along the way. Happy batch filing!

Got a favorite batch file utility you’d like to share? Questions about how to customize these scripts to your needs? Know of other good batch command resources? Share them in the comments. That’s where we can all learn and help each other. After all, we’re all in this together.

Image Credits: MS-DOS System, Time Limit, Delete Files, eBooks to Tablet via Shutterstock, Lottery Balls and Ticket from Lost via Flickr.

  1. Hawk
    March 23, 2016 at 8:42 pm

    Perl programmers can take advantage of their -x command line switch. -x will cause the Perl interpreter to ignore everything from the start until it finds a line that has "#!" and "perl" in it. Now you can write batch code at the top and Perl code at the bottom, all in the same file. The batch code does what it needs to do, fires off Perl, and Perl continues on where the batch script left off! I once had a unique situation where I actually had to do this. It worked perfectly!

    • Guy McDowell
      March 30, 2016 at 12:22 am

      I will have to remember that! It just might come in handy one day.

  2. Pat
    January 2, 2016 at 8:51 pm

    In Windows7 I ran a batch file that played a sound file. In Windows 10 the bat works but the sound comand does not. I've tried various versions of the start command but it leaves an open music player window. Runing a program with arguments doesn't seem to work.
    Any ideas?

    C:\WINDOWS\system32\wizmo.exe play=D:\Sound\chord.wav
    (wizmo is from

  3. Gudmundur Steinthor Jakobsson
    July 7, 2015 at 4:13 pm

    skip the goto and just limmit to 4 characters with %ran:~0,4%

  4. Gudmundur Steinthor Jakobsson
    July 7, 2015 at 4:05 pm

    format the %random% variable to only show 4 fyrst letters %random:~0,4%

    • Guy McDowell
      July 10, 2015 at 7:03 pm

      I'm going to have to try that. Nice work.

  5. Federico Durán
    July 3, 2015 at 4:30 pm


    Before every line of code write another line beginning with "REM" describing what the code do. Even the lines with code that is obvious TODAY. If you don't, a week from now you will find yourself staring at your batch and thinking "WTF am I doing in this step?". Of course, this applies to all source code. I also indent remarks to increase legibility.

    For example:
    REM Set a variable with the string to be replaced (so it can be maintained in one place and not all over the script):
    SET old=.UploaderGuy.PD

    • Guy McDowell
      July 3, 2015 at 4:48 pm

      Excellent advice!

      It's the first lesson in any programming course. Unfortunately, it seems to be the first thing to disappear when you hit the work world.

  6. Christopher HasARightToPrivacy
    July 1, 2015 at 4:15 pm

    I've always found bash lacking and cryptic but found bash scripting a little easier to understand. I wish Microsoft would just build a new OS starting from nothing but a Linux kernel :-)

    • Christopher HasARightToPrivacy
      July 1, 2015 at 4:16 pm

      Sorry, that's: "I've always found BATCH lacking"

    • Guy McDowell
      July 2, 2015 at 4:36 pm

      It is limited, true. And cryptic, especially to a non-programmer, non-sysadmin person. It's a good tool for little things though.

      BASH scripting is definitely worth learning for people who want to do anything even slightly complex, or a lot of different scripts for different jobs.

      I can see why they wouldn't want to build an MS distribution of Linux. It is a money game for them. Yet even if MS built from scratch and incorporated what they've learned over the years, they should be able to come out with something very impressive.

      • Christopher HasARightToPrivacy
        July 4, 2015 at 10:40 pm

        "I can see why they wouldn’t want to build an MS distribution of Linux" - Both Apple and Google did it with great success. I don't see any reason why Microsoft couldn't.

        • Guy McDowell
          July 7, 2015 at 2:39 pm

          Definitely they could, and that would be a good way to go.

          They might not want to because of business or policy issues. Not technological necessarily. Who knows why they do what they do? That's a rhetorical question. ;)

  7. GodSponge (EB)
    July 1, 2015 at 6:24 am

    With a little tweaking you can use the numbers less than 1000.

    @echo off
    set /a ran=%random%
    if /i %ran% GTR 9999 goto :start
    if /i %ran% LSS 1 goto :start
    if /i %ran% LSS 10 goto :tens
    if /i %ran% LSS 100 goto :hund
    if /i %ran% LSS 1000 goto :thou

    echo Batch chose the number %ran%
    goto :end

    echo Batch chose the number 0%ran%
    goto :end
    echo Batch chose the number 00%ran%
    goto :end
    echo Batch chose the number 000%ran%
    goto :end


    You can also add goto :start after the pause to keep getting more numbers.

    • Guy McDowell
      July 1, 2015 at 3:19 pm

      Nice tweak! Well done!

Leave a Reply

Your email address will not be published. Required fields are marked *