- /* steve jansen */
- // another day in paradise hacking code and more
- Windows Batch Scripting: Getting Started
- Getting Started with Windows Batch Scripting
- Launching the Command Prompt
- Editing Batch Files
- Viewing Batch Files
- Batch File Names and File Extensions
- Saving Batch Files in Windows
- Running your Batch File
- Comments
- Silencing Display of Commands in Batch Files
- Debugging Your Scripts
- Comments
- Guides
- Recent Posts
- Social Stuff
- How to Write a CMD Script
- Related
- Understanding CMD and Written Commands
- Understanding CMD Scripts
- Using a Script CMD to Open Notepad
- Creating Your First Script CMD File
- Using Echo and Echo Off
- Creating a Text File Script
- Creating a Systems Information Script
- Using Scripts to Shut Down Your Computer
- Backing Up Files With a CMD Script
/* steve jansen */
// another day in paradise hacking code and more
Windows Batch Scripting: Getting Started
Getting Started with Windows Batch Scripting
Windows batch scripting is incredibly accessible – it works on just about any modern Windows machine. You can create and modify batch scripts on just about any modern Windows machine. The tools come out of the box: the Windows command prompt and a text editor like Notepad.exe. It’s definitely far from the best shell scripting langauge, but, it gets the job done. It’s my “duct tape” for Windows.
Launching the Command Prompt
Windows gurus launch the command prompt using the keyboard shortcut Windows Logo Key + R (i.e., “Run”) > Type cmd.exe then Enter . This is way faster than navigating the Windows Start Menu to find the Command Prompt.
Editing Batch Files
The universal text editor for batch files is Notepad ( Windows Logo Key + R > Type notepad then Enter ). Since batch files are just ASCII text, you can probably use just about any text editor or word processor. Very few editors do anything special for Batch files like syntax highlighting or keyword support, so notepad is good enough fine and will likely be installed on just about every Windows system you encounter.
Viewing Batch Files
I would stick with Notepad for viewing the contents of a batch file. In Windows Explorer (aka, “My Computer”), you should be able to view a batch file in Notepad by right clicking the file and seleting Edit from the context menu. If you need to view the contents within a command prompt window itself, you can use a DOS command like TYPE myscript.cmd or MORE myscript.cmd or EDIT myscript.cmd
Batch File Names and File Extensions
Assuming you are using Windows XP or newer, I recommend saving your batch files with the file extension .cmd . Some seriously outdated Windows versions used .bat , though I recommend sticking with the more modern .cmd to avoid some rare side effects with .bat files.
With the .cmd file extension, you can use just about filename you like. I recommend avoiding spaces in filenames, as spaces only create headaches in shell scripting. Pascal casing your filenames is an easy way to avoid spaces (e.g., HelloWorld.cmd instead of Hello World.cmd ). You can also use punctuation characters like . or — or _ (e.g. Hello.World.cmd , Hello-World.cmd , Hello_World.cmd ).
Another thing with names to consider is avoiding names that use the same name of any built-in commands, system binaries, or popular programs. For example, I would avoid naming a script ping.cmd since there is a widely used system binary named ping.exe . Things might get very confusing if you try to run ping and inadvertently call ping.cmd when you really wanted ping.cmd . (Stay tuned for how this could happen.) I might called the script RemoteHeartbeat.cmd or something similar to add some context to the script’s name and also avoid any naming collisions with any other executable files. Of course, there could be a very unique circumstance in which you want to modify the default behavior of ping in which this naming suggestion would not apply.
Saving Batch Files in Windows
Notepad by default tries to save all files as plain jane text files. To get Notepad to save a file with a .cmd extension, you will need to change the “Save as type” to “All Files (.)”. See the screenshot below for an example of saving a script named “HelloWorld.cmd” in Notepad.
SIDEBAR: I’ve used a shortcut in this screenshot that you will learn more about later. I’ve saved the file to my “user profile folder” by naming the file %USERPROFILE%\HelloWorld.cmd . The %USERPROFILE% keyword is the Windows environmental variable for the full path to your user profile folder. On newer Windows systems, your user profile folder will typically be C:\Users\ . This shortcut saves a little bit of time because a new command prompt will generally default the “working directory” to your user profile folder. This lets you run HelloWorld.cmd in a new command prompt without changing directories beforehand or needing to specify the path to the script.
Running your Batch File
The easy way to run your batch file in Windows is to just double click the batch file in Windows Explorer (aka “My Computer”). Unfortunately, the command prompt will not give you much of a chance to see the output and any errors. The command prompt window for the script will disappear as soon as the script exits. (We will learn how to handle this problem in Part 10 – Advanced Tricks ).
When editing a new script, you will likely need to run the batch file in an existing command window. For newbies, I think the easiest foolproof way to run your script is to drag and drop the script into a command prompt window. The command prompt will enter the full path to your script on the command line, and will quote any paths containing spaces.
Some other tips to running batch files:
- You can recall previous commands using the up arrow and down arrow keys to navigate the command line history.
- I usually run the script as %COMPSPEC% /C /D «C:\Users\User\SomeScriptPath.cmd» Arg1 Arg2 Arg3 This runs your script in a new command prompt child process. The /C option instructs the child process to quit when your script quits. The /D disables any auto-run scripts (this is optional, but, I use auto-run scripts). The reason I do this is to keep the command prompt window from automatically closing should my script, or a called script, call the EXIT command. The EXIT command automatically closes the command prompt window unless the EXIT is called from a child command prompt process. This is annoying because you lose any messages printed by your script.
Comments
The official way to add a comment to a batch file is with the REM (Remark) keyword:
The power user method is to use :: , which is a hack to uses the the label operator : twice, which is almost always ignored.
Most power authors find the :: to be less distracting than REM . Be warned though there are a few places where :: will cause errors.
For example, a FOR loop will error out with :: style comments. Simply fall back to using REM if you think you have a situation like this.
Silencing Display of Commands in Batch Files
The first non-comment line of a batch file is usually a command to turn off printing (ECHO’ing) of each batch file line.
The @ is a special operator to suppress printing of the command line. Once we set ECHO’ing to off, we won’t need the @ operator again in our script commands.
You restore printing of commands in your script with:
Upon exit of your script, the command prompt will automatically restore ECHO to it’s previous state.
Debugging Your Scripts
Batch files invole a lot of trial and error coding. Sadly, I don’t know of any true debugger for Windows batch scripts. Worse yet, I don’t know of a way to put the command processor into a verbose state to help troubleshoot the script (this is the common technique for Unix/Linux scripts.) Printing custom ad-hoc debugging messages is about your only option using the ECHO command. Advanced script writers can do some trickery to selectively print debugging messages, though, I prefer to remove the debugging/instrumentation code once my script is functioning as desired.
Posted by Steve Jansen Mar 1 st , 2013 batch, scripting, shell, windows
Comments
Hi, I’m Steve. I’m a software developer loving life in Charlotte, NC, an (ISC) 2 CSSLP and an avid fan of Crossfit.
And, no, I’m not Steve Jansen the British jazz drummer, though that does sound like a sweet career.
Guides
Recent Posts
Social Stuff
- @steve-jansen on GitHub
- @steve-jansen on StackOverflow
- @steve-jansen ProTips on Coderwall
- @steve-jansen on Microsft Connect
- @steve-jansen on ASP.NET User Voice
- Subscribe via RSS
Copyright © 2015 — Steve Jansen — Powered by Octopress
How to Write a CMD Script
Related
If you have every used the Command Line, or CMD, interface in Windows, you probably have some idea of the powerful things it can do. Creating your own CMD scripts, you can do even more, but faster.
A CMD script does the same thing as if you typed commands into the CMD window. If you want to do something on a regular basis, such as telling Windows to turn off your computer after an hour, you can write a script and then you can activate the script whenever you want to run it.
Understanding CMD and Written Commands
In the early days of personal computing almost everything was done by typing command_s into a command line interface. If you wanted to open a program, you had to type the name of the program into the command line. Today, you can simply click or touch an icon on your screen to perform most actions. But Windows still accepts type-written commands in the CMD utility. You can write commands_ to open programs, add or change account permissions, back up files or get information about your computer using the CMD window.
Understanding CMD Scripts
The Command Prompt utility in Windows can be opened at any time, simply by typing «cmd» in the Windows Start menu. Here, you can type all sorts of commands to open programs, change settings and make tweaks to how Windows and its programs perform. In Microsoft’s long history of operating systems, CMD i_s a relative newcomer. In MS-DOS, before Windows was released, when you wanted to run a script, you would save it as a .bat file. While you can still save files with that extension today, most people use the .cmd extension._
Using a Script CMD to Open Notepad
To create and save a CMD switch, it’s best to use a basic text editor. Using a word processor like Microsoft Word makes saving the file a hassle. Notepad is much easier to use. So to demonstrate how CMD works, let’s open use it to open Notepad.
- Type CMD in the Windows Start menu and press Enter to open CMD.exe.
- Change the directory from your current username folder to the base directory by typing «cd\» and pressing Enter. It should now read «C:\>» before the blinking cursor.
- Type the following line and pressEnter:start «c:\windows\system32» notepad.exe
As soon as you press Enter, you will see Notepad open. The command you entered has told Windows to start the notepad.exe program, which is located in the system32 folder, which is inside the Windows folder, on the C: drive. CMD commands are not case-sensitive so you can use lowercase or uppercase letters interchangeably.
Creating Your First Script CMD File
Now that Notepad is open, create your first CMD script file by typing the same line you used in the CMD window into notepad: start «c:\windows\system32» notepad.exe
Save the batch file to your desktop by selecting «Save As» from the File menu. Name the file «firstscript.cmd» and click «Save.» Notepad script commands must be saved with the .cmd extension, rather than the default .txt extension.
Double-click the new CMD file on your desktop. You will see the CMD window open for a fraction of a second and then close as Notepad is launched.
This is hardly a useful script, since a desktop shortcut does the same thing. To create something more useful, let’s edit the file so that it creates a new text file on your desktop listing all of your programs.
Using Echo and Echo Off
While the CMD window wasn’t open long enough to see it, by default it will always display the text that was entered in the CMD file when it runs. For longer scripts, this can be a nuisance, so it’s generally good form to turn this off by using the Echo Off command in the first line of the CMD file. By itself, Echo Off disables the display of any text that follows it. To make the Echo Off command apply to itself, put an @ symbol in front of it. Thus, your two-line CMD script would be:
@echo off
start «c:\windows\system32» notepad.exe
Creating a Text File Script
This CMD script will list all the files you have in your Program Files folder and put that list in a new text file.
- Open Notepad. Type «@echo off«in the first line and press Enter.
- In the second line, type: dir «C:\Program Files» > list_of_files.txt
- Select «Save As» from the File menu and save the file as «program-list-script.cmd.»
- Double-click the new text file on your desktop to see the list of files and folders.
The text file will appear in the same folder where the script file itself is. So if the script file is on your desktop, the list-of-files.txt file will also appear on your desktop.
If you want to change the folder where the text file is placed, you can specify its own folder in the script. For example, if you want it to be placed in your Documents folder, use: dir «C:\Program Files» > C:\Users\David\Documents\list_of_files.txt
Creating a Systems Information Script
If you want to use a script to give you needed information, it’s not always necessary to produce a text document with a script. You can have the information posted directly in the CMD window.
The example script below will give you basic information about your computer, including the operating system and version number, the BIOS version, the total physical memory and your computer’s network address. To use the script, type or copy the lines below into a new Notepad file and save it with the .cmd file extension, such as «my_computer_info.cmd.»
In this example, ECHO OFF is used to prevent the CMD window from displaying the script.
The ECHO command is used to display specific text, as well as some equal signs (===) as lines to organize the information in sections.
To insert a comment for your own use — without it affecting the script or appearing in the CMD window — type two colons first. Anything in the same line following » :: « will be commented out from the script.
The PAUSE command directs the CMD program to stay open. Pressing any key on your keyboard will close the window.
@ECHO OFF
:: This CMD script provides you with your operating system, hardware and network information.
TITLE My System Info
ECHO Please wait. Gathering system information.
ECHO OPERATING SYSTEM
systeminfo | findstr /c:»OS Name»
systeminfo | findstr /c:»OS Version»
ECHO BIOS
systeminfo | findstr /c:»System Type»
ECHO MEMORY
systeminfo | findstr /c:»Total Physical Memory»
ECHO CPU
wmic cpu get name
ECHO NETWORK ADDRESS
ipconfig | findstr IPv4
ipconfig | findstr IPv6
PAUSE
Using Scripts to Shut Down Your Computer
Normally, when you shut down your computer, it happens instantaneously. Suppose, however, that you’re listening to an audiobook or watching a training video — and you know that you will fall asleep after an hour. You can use a CMD script to tell your computer to shut itself down, after a specified period of time, using the shutdown command.
When you use the shutdown command, you need to include two additional switches, or subcommands. The first tells the computer to either shutdown or restart. You can use either -s or — r. The second tells the computer how many seconds to wait before performing the command. For this you use -t, followed by the number of seconds.
To shutdown the computer in one second, use: shutdown -s -t 01
To restart the computer in eight seconds, use: shutdown -r -t 08
To shutdown the computer in two hours use: shutdown -s -t 7200
Backing Up Files With a CMD Script
If you find it tedious to back up your files to a second storage device, using a CMD script makes the process a breeze. For this, use the Robocopy command. For example, if you want to back up all of the files in your Documents folder onto a removable storage device, you can write the command in a CMD file and then — at the end of the day — simply double click the file to activate it.
The Robocopy command needs to know, first — which folder you want to copy and, second — where you want the copy placed. Both the source and destination need to be in quotation marks.
If you’re not certain what your drive letters are, open File Explorer and click on «My Computer.»
For example, if your User name is MyName, your Documents folder is in your C: drive and your Backup folder is in a removable storage D: drive, then the command would be:
robocopy D:\Users\MyName\Documents F:\Backup /XA:H /W:0 /R:1 > F:\Backup\backup.log
This example is a bit more complicated, since Robocopy offers you a lot of options.
D:\Users\MyName\Documents: the folder you want to back up.
F:\Backup: the location of your Backup folder.
/XA:H: ignores hidden files.
/W:0: waits zero seconds between retries, instead of the default 30 seconds.
/R:1: retry only once if the file is locked.
> F:\Backup\backup.log: create a backup log placed in the Backup folder.
Note that because this is a mirror backup, if you delete files from the source folder, they will be deleted from the Backup folder the next time you use the script. It would be a good idea to explore additional switches available for Robocopy, so that you ensure that you backup your files the way that works best for you.