Most these examples work all the way back to Win9x, and some all the way back to DOS 5. There are often easier ways of performing these tasks with the newer operating systems.
User Input  Timing  Counting  Network  Windows  Disks  Directories  Files  Sounds  MultiMedia  Installations  Miscellaneous 

User Input

Get user input from batch file

Sure, you've done it, but can you do it without having to hit a Ctrl-Z, without ANSI, without a debug script, and without a separate "set" file?

Get user input and mask passwords with HTML

HTML forms can mask passwords as you enter them, so use forms! Here I show you how to have your batch file create a username/password form, then use Windows Scripting to read the contents of that form and transfer the results back into a batch file. As shown, it uses the environment, so you may need to modify things if your target computers don't have room.

Get user input and mask password with HTA

HTML Applications (HTA files) can do everything ordinary HTML can, but there is no need to separate the HTML from the scripting in order to save the results to the hard drive. Like the above HTML method, this creates a batch file named "userin.bat" in the "temp" directory which can be called by your batch file to retrieve the data.

Mask passwords with QBASIC

QBASIC allows you to grab user input without echoing it to the screen. This makes it easy to throw an asterisk up for every character that gets entered. Again, this code stores the password in the environment for your batch file to use. FYI, Win9x boxes don't come with QBASIC installed by default. See here for how to get QBASIC and here for how to install it automatically.

Get user input from an NT batch file

All the old tricks fail. Luckily, QBASIC can be used and is standard equipment in NT. Windows Scripting works better if you have it.

Accept arguments in any order

Simon Richardson shows how to use structured batch programming (as best as batch can do it) to collect arguments. Then I show how to break that structure.

Accept arguments in any order

Fred Fisher said he could improve on the above method to collect arguments. I think you'll agree he did! He does it with a few more IFs and a lot less GOTOs. He demonstrates three separate argument types. One is a switch, another takes one argument, and the last takes two separate arguments. You can easily simplify (or extend) the code for any number of arguments each taking any number of parameters. Then, just to show that he could do the same thing by using subroutines, Fred sent along another example.

How to get around the "Do you really want to do this?" prompt.

Have your batch file send the desired answer..

How to simulate typing to any program.

Send your program keystrokes whether it is a DOS or Windows program. This isn't "User Input", but is more along the lines of simulating a user who isn't there. Great for automating programs that weren't designed to be automated.

Timing

Wait for a program to finish

Your batch file runs a Windows program, but you need it to not do anything else until after that Windows program finishes. The general answer is to use the START command with the /WAIT option like this:
start /wait notepad.exe
However, some programs still won't "wait" properly. In those cases, read the advice I give on my scripting web page about Compressed Executables.

Make a time delay

Put your computer to sleep for a while. At least put the particular DOS window you are in to sleep.

Time delay and For-Next loops

Demonstrates two things: using CHOICE to effect a one-second time delay, and using  environment variables to track nested "for-next" loops in batch files (yes, you can!) to multiply the one second up to sixty seconds (actually sixty seconds plus batch processing time). And what did I decide this file should do with it's one-minute delay? Why, display the time, of course!

Run a specified program only on certain days at boot time.

This demo makes use of two tricks: It reads a custom INI file, and it puts the current day into the environment.

Counting

Incrementing

It isn't real math, but batch files can add one to a number to help you set up loops or generate sequential file names or whatever you want.

Generate a random number

Grab the hundredths digit from the time.

Network

Hosts File: Finding Expired Hosts

Windows 2000 or newer required   If you (mis)use your HOSTS file by listing all the machines you don't want to connect to, you might wonder if all the machine names you've collected are still valid! For every machine in your HOSTS file, this batch file will use the NSLOOKUP command to see if your DNS server can locate a matching IP address. Any machine that no longer has an IP address will be added to a list. The advantage of using NSLOOKUP over something like PING is that your HOSTS file can continue to provide blocking services while it is being tested.

Hosts File: Removing Expired Hosts

Windows 2000 or newer required   If you have a list of  machines you'd like to remove from your HOSTS file (like the list generated by the above batch file!),  this batch file will construct a new HOSTS file that doesn't have the machines in the list. Your original HOSTS file isn't modified. The final step of actually copying or pasting over the new data is rightly left up to you.

Network Security Scan

Windows 2000 or newer required   Scan all 254 addresses in your current subnet or pass it an IP and it will scan that subnet instead. It will produce a detailed report as well as allow you to display all open shares and web servers (like the web server built into a router).  The complete scan takes less than three minutes. Why do it? Well, I wondered just how much "snooping" could be done using only what was built in to Windows 2000. You don't need to install any additional programs. It was for... ummm.... driving around with a wireless laptop that isn't allowed to have any "extra" programs installed on it. But I've noticed it also works quite nicely on my personal home network. Amazingly, ninety percent of home wireless systems have no passwords. I have to assume the owners are intentionally donating their internet service. So -- what else are they donating? If you try to open a share and it asks for a user name and password, look at the report in the "NBSTAT" section. Try the names associated with that computer and leave the password blank. If you want to get the wireless router's upstream IP address (so you can scan that subnet looking for hardwired computers), try logging in to the wireless router's web server. If you need a user name and password for the router, try to find the brand of the router. It's probably displayed as part of the login. You could also enter the first three bytes of the MAC address (like 00-04-5A, which you can find in the "ARP" section of the report) in an OUI lookup like http://standards.ieee.org/regauth/oui/index.shtml. Once you know the manufacturer, visit their web site (using your free wireless internet!) and download the manual. It will tell you the default factory user name and password. It shouldn't be this easy. Make sure YOUR network isn't this wide open.

FTP scripting

The FTP program can be scripted. Assuming you know how to type FTP commands, this tells you that little bit more you need to generate a script -- or turn your script into a batch file. Now you can set up FTP script batch files to automate your downloads.

McAfee (Network Associates) End-User Antivirus Update

When your automatic updater becomes a pest by telling you it's time to spend more money, disable it and use a batch file like this to automatically download and run the latest "SuperDAT" update. 

McAfee (Network Associates) Commercial Antivirus Download

Administrators need to know when a new update is available. And they need to download that update. Automatically. Even though the name changes every time.  Here are directions on how to create a batch file you can schedule to run as often as you want. It will look for an update and grab it, rename it to your standard name, then notify you. Or whatever else you want.

Symantec (Norton) Antivirus Update

This batch file will download and run the daily antivirus "intelligent updater" file from Symantec. Windows 2000 or newer is required because of the environment variable techniques used to identify the most recent update file. 

What is my IP address

Three different ways to get your IP address from inside a batch file.

What is my Server IP

No, it's not a mind reader. Someone told me they had hundreds of subnets, but the file server in each subnet had an IP address of 21 in every case. He wanted a way to run the same batch file on all workstations at login time that would locate the IP address of the local file server. It had to work on NT and 9x workstations, and it just had to replace the last part of the workstation's dynamic IP with 21. So I wrote this. It is NOT pretty, but that's what compatible code looks like. A pure NT solution can be done in three lines.

Ping an entire subnet and find the live computers.

This demonstrates how to increment a number from 1 to 255 and build a loop based on the incremented number.

Find all FTP servers

Actually just the FTP servers on any small subnet. You build a loop that counts from 1 to 254 and let it script the FTP program. Three batch programs zipped up. You configure and run hunt.bat, it calls the other two.

Wait for your friend's dynamic web site

Keep pinging it until it responds. Then launch whatever you want. Automatically.

Enter your login password automatically

Well... only if you use a really lame network client.

Windows

Get the user name

Shows how to grab the current Windows or network user name out of the system registry.

Get the user name

Parse the output of the NET command and use the first word as the name of a batch file.

Get the user name

Parse the output of the NET command, but use DEBUG instead of relying on the first word.

Get the computer name

Parse the output of the NET command and use DEBUG to strip the leading // from the result.

Track when anybody logs in

How to get a program to run when Windows 9x starts or a new user logs in.

Is Windows Running

Deciphering the output of the MEM command to tell a batch file what kind of an environment it is running in

How to shut down a Windows program

This is actually a generic "How to control another app" question. It isn't DOS, but it can be done.

Running a batch file after Windows shuts down.

It's a great time to run last-minute tests or delete temporary files.

Exit windows and shut down your computer

from a batch file? Rundll.exe can do the impossible.

Print multiple files or multiple copies

Even though it may be a Windows program that does the printing, you can automate the process with a batch file.

How to make a DOS window close

after your batch program finishes. It only takes two lines of code!

How to make a DOS window run minimized or be invisible

Using a PIF file, the START command, or Windows Scripting.

Disks

Is there a disk in the A: drive?

Using the /f option of command.com allows you to find out without crashing your batch program.

Find the CDROM

Not really. Actually, how to search all drives to find which one has a certain file.

How to format a disk automatically

Just about the worst thing you would want to automate, but it's your life.

Find Disk Size

Use the DEBUG command to trim the output of the CHKDSK command to get disk size.

Find Disk free space

Use the DEBUG command to trim the output of the DIR command to get the free space.

How to open the CD drawer

I didn't figure this one out, and I have no real use for it, but it's just too cool! Not for NT because, well, because.

Directories

Save the current directory

Done without using the environment. Put this "pushpath.bat" file in your path. It will create the matching "poppath.bat". You run pusshpath first, then do something that changes your current directory, then run poppath to reset the directory to where you started.

Run a command in every subdirectory

Automatically change to each subdirectory on your drive (or part of it) and run whatever command you want.

Find the directory Java is in

People who write Java aren't usually batch programmers too! I've seen too many hard-coded batch files that fail unless Java is installed in specific locations. This batch file will read the registry to locate the most current Java runtime directory, then converts that into a short path. You could use that path info to run Java directly or to just set a PATH statement. Works under WinNT/2000, and fails gracefully under Win9x.

Find the directory your batch file is in

Again for Java programmers who put their batch files in the same directory as their JAR files, but need to know the short path to that directory so they can set their CLASSPATH environment variable. This one works under both Win9X or NT/2000.   

Files

Convert List to URLs

Convert a plain text list of URLs to individual URL files (Internet shortcuts). This is appropriate if you only have one URL per web site.

Convert List to BATs

Convert a plain text list of URLs to batch files. Each batch file will open multiple tabs in your browser (as needed) to display all the web pages in your list for a particular site.

When was a file last accessed?

Use the DEBUG command to trim the output of the DIR /V command to get just the access date.

Get the root name of a file

Only works on short names, but if you ever want to dump the file extension, here's a way.

When was a file created?

Use the DEBUG command to trim the output of the DIR command to get the file created date.

Read and write to INI files

A "pure" batch file solution requiring nothing more than standard DOS. It won't work with complex INI files like WIN.INI, but is instead intended for simple one-section private INI data files. Store all your stuff in an INI file instead of in the environment!

Copy the most recent file

When a process automatically generates files, it can really help to have a single file name for the most recently generated file.

Get file sizes in HEX

How to use DEBUG to retrieve the lower 16 bits (64k) of a file's size. Although it isn't done, I show how to get the upper 16 bits as well.

Comparing file sizes

Everybody wants to move big files or delete small ones. How is a batch file to tell? You'll wish I just gave you the answer, but I'm forced to teach you the techniques instead. DOS has no native way of comparing, so we have to find ways of using DOS' sorting abilities to do the job.

Long and short file names

Shown are several tricks for converting back-and-forth from long to short names, getting the drive letter, and getting the file extension. This isn't made for reading. Just save it as a BAT file and drop a file on it with Explorer. If it gives you what you want, steal the appropriate code section.

How to make a randomly-named file

Or at least how to get an almost random filename guaranteed not to exist in your TEMP directory.

Rename Files with time and date

Many programs generate files which need to be renamed with unique names. Time and date usually do the trick.

Delete duplicate files

If you download binaries (music, photos, etc.), you can end up with lots of files that are identical except for the name. Here's a Windows2000/XP solution that will delete duplicate files. If you don't want to delete arbitrary duplicates, you can just replace the line that says:
if not errorlevel 1 del %fnameold%
with one that says:
if not errorlevel 1 pause
and handle the situation manually.

Rename all files from one extension to another

Shown here renaming VXE files to EXE by creating a list of files to be changed and changing them one-at-a-time

Rename all files from one extension to another

Shown here renaming VXE files to EXE by changing into every subdirectory one-at-a-time and doing a wildcard rename.

Sounds

Make a beep

You can misuse the CHOICE command or spin up a quick QBASIC program. No ANSI needed.

Play sounds

Annoy the cat. Play all your sounds with just enough delay between sounds to let the cat relax. 

MultiMedia

MP3 Recode

Takes a directory full of MP3 files and converts them to mono, compresses them, and recodes them at (hopefully) a lower bit rate. Written to allow me to fit way more podcasts and audio books on whatever player I have. The conversion to mono is tested both ways (normal and out-of-phase) to see which produces the best results. The compression stops you from having to keep jumping for the volume control because of volume differences between the "bumpers" and the main body of the story. The lower bit rate allows for a much smaller file while still producing excellent quality voice.

Convert a DVD rip to play on a phone

This batch file will take a DVD rip (typically a DivX avi file) and crop and recompress it to phone size. It creates a 320x240 15FPS MP4 H264 at 100Kbps. This is fairly harsh compression,  but it makes a very small 120MB movie and looks great on a phone. Naturally, because this is a batch file, you can change it to suit you!

Installations

Insure Visual Basic 5 exists on a user's machine

Not just test for it, but download and start the installation program up too! Just stick this code in front of any batch file that needs the VB5 runtime.

Insure QBASIC exists on a user's machine

Not just test for it, but download and install it automatically too! Just stick this code in front of any batch file that needs QBASIC.

Miscellaneous

Is a COM port available

Check to see if a com port is available before proceeding.

Hide your batch file code

What if you have to embed a password or something else you don't want seen in your code?

Registry operations

I always meant to expand my entry on this subject, but never got around to it.  It ought to give you a start.

RunDLL and RunDLL32

Batch programs can do the impossible with these commands. Unfortunately, finding things you can actually do is like looking for easter eggs. The list of things you'd actually ever WANT to do is pretty small. I present my UNFINISHED list of commands. I'll only put out the effort to finish it if I hit another project where I need it.

Put the time into the environment

This batch file shows the trick of using a command output as a command line. In this case the "Current Time..." output of the TIME command is used to call a batch file named "CURRENT.BAT".

Read the output of DOS commands

Use FIND.EXE and CHOICE.COM (if needed) to make decisions based on the output of any DOS command. This isn't the discovery of the year, but it can be a very handy trick to know! How would you use this? Tell if ANSI is in memory. Tell if Windows is running. And all automatically!

Subroutines in batch files

Structured programming is here at last! The batch file simply CALLs itself and passes the name of a label it wants to GOTO. Each label contains the standalone "subroutine" code and exits when finished, returning control to the calling incidence. Sound confusing? Just take a look at the simple code and run it.

Inner Peace

No, I didn't do this! I helped out with a few tips. It's just as odd as it sounds and implementing it in DOS batch is even odder. If you run it, it will try to improve your "Inner Peace". If you read it, it goes a long way towards being a course in how to write batch files.

Lost? Look at the site map.

Bad links? Questions? Send me mail.

Google
Yahoo
Ask Jeeves