My career as an IT professional has been filled with reminders that almost everyone I interact with is much younger than I. One advantage I gain from my age and my long history with computers is an automatic reflex to use command-based tools whenever I have to perform a task. Often, when I interact with administrators who are struggling to create complicated scripts, I can't resist saying, "A batch file would be easier, quicker, and work just as well." I get some strange looks, because so many administrators are too young to have had experience with DOS, and they aren't quite sure what a batch file is. (I tell them a batch file is simply a text file containing DOS commands.) Whenever I write about batch files, I get a ton of email asking for more information about creating and using these handy utilities.

Mapping Drives from the Command Line
Most of the queries I receive from administrators ask about mapping drives throughout the network to make sure users access the appropriate folders on remote computers. (These admins often add that they try to script the solution but find the task more work than they anticipated.) They also want to know if there's a secret to mapping a drive to a folder that isn't shared. The answer to both questions is to use the command line.

You can map drives from the command line with the Net Use command. Type

net use

with no switches at a command prompt and you'll receive information about the currently mapped drives that also lets you know which drive letters are available. The following information displays:

  • The current state of the Reconnect at Logon option, specified either by the text "New Connections Will Be Remembered" or "New Connections Will Not Be Remembered."
  • The current status of each connection, specified either by OK (which means connected) or Disconnected.
  • The drive letter.
  • The mapped folder's name in Universal Naming Convention (UNC) format.
  • The network type (usually Microsoft Windows, but if you're running Novell NetWare client software and mapping drives to a NetWare server, the network listing is NetWare).

Usually, mapped drives are marked Disconnected when you first boot the computer, but as soon as you access the mapped drive its status automatically changes to Connected. You can access the mapped drive in My Computer or by entering the drive letter in the command window, as follows:

k:

Don't forget the colon.

Creating a Mapped Drive
To map a shared folder to a drive letter, enter on the command line

net use d: \\\

Substitute the drive letter you want to assign to the share for d. If any folder in the path has a name that includes a space, enclose the entire path, including the opening double backslash, in quotation marks. Windows returns the message The Command Completed Successfully. If you're a skeptic, use the Net Use command to make sure your new mapped drive appears in the list the command returns.

Whether or not your new mapping reconnects at logon depends on the current state of the Reconnect at Logon option. You can set the reconnection option you prefer with the /persistent: \[yes/no\] switch. For example, to reconnect at logon, enter

net use f: \\/persistent: yes

To map a drive for the current session only, enter

net use f: \\ /persistent: no

The reconnection option you select becomes the default state of the Reconnect at Logon option (including the option displayed on the GUI version of the Map Network Drive dialog).

Mapping Drives to Unshared Folders
Unlike the mapping function in the Windows GUI, the Net Use command doesn't limit you to mapping shared folders. To map an unshared subfolder of a shared folder or any folder on a shared drive, enter on the command line

net use f:
  \\\\

The ability to map a resource that isn't explicitly shared is useful because you can share a drive, then map any or all of the folders on that drive. Of course, you must be judicious about security in such an environment, so make sure the permissions in the target unshared folder are set appropriately.

Removing a Mapped Drive
To remove a mapped drive, enter

net use : /delete

substituting the appropriate drive letter for d. The system returns the message

d: was deleted successfully

Batch Files for Mapping Drives
The Net Use command gives you the ability to use batch files to create mapped drives. Administrators can use logon batch files that contain the Net Use command to set mapped drives for users. Mapped drives make it easy for users to access the appropriate folders for specific software and data. For example, for users who work in the company database, you might have a logon script with the following contents:

net use g: \\
net use h: \\\

Name the file whatever you want (it must have a .bat extension), and copy it to the logon script directory on your domain controller (DC). The default location for logon scripts on a DC is %SystemRoot%\ SYSVOL\sysvol\\scripts. The scripts subfolder is automatically shared with the share name NETLOGON (which is the name that appears on remote computers when you expand the DC in My Network Places).

Be careful not to map the drive letter that's in use for User Home Drives. During user logon, Windows maps the home drive first, before running any logon scripts from the scripts subfolder. If your logon script tries to map a drive letter that's already used, the system returns the error The local device name is already in use.

Batch Files for Computer Maintenance
I use batch files to take care of general maintenance and cleanup tasks. For example, at the end of the day I remove all backup copies of Microsoft Word documents I've worked on. I like the backup feature in Word, but when I've successfully saved the current copy, I no longer need the backup copy, and I want to regain the disk space that the backup copy uses. I use the following command to remove the backup files. Notice that folders with names that contain spaces are enclosed in quotation marks.

del c:\"documents and settings" kathy.ivenseast\"my documents"\*.wbk
 /s/f/q

The /s switch tells Windows to delete the specified files from all subdirectories. The /f switch tells Windows to force the deletion of read-only files. The /q (quiet mode) switch tells Windows not to ask for confirmation when a wildcard is used with the command. I use the following commands to copy my accounting software files, my Eudora mailboxes, and my Eudora address book to their own folders in My Documents.

Copy C:\QuickBooks\"company files"\*.qbw
  C:\"Documents and Settings"  kathy.ivenseast\"my documents"  QBBackup /y
Copy C:\Quicken\ivens.* C:\"Documents and
  Settings"\kathy.ivenseast\"my
  documents"\QuickenBackup /y
Copy C:\Eudora\data\*.mbx C:\"Documents
  and Settings"\kathy.ivenseast\"my
  documents"\EudoraBackup /y Copy
C:\Eudora\data\nndbase.txt
  C:\"Documents and Settings"  kathy.ivenseast\"my documents"  EudoraBackup /y

The /y switch tells Windows not to ask for confirmation when copying over existing files. I use this approach to move any file from any folder into My Documents, to take advantage of the fact that I back up the My Documents folder daily. Incidentally, some software lets you select a data folder that resides outside of the folder in which the software is installed. In that case, you can create the data folder in My Documents so it's ready for easy backup.

Batch Files for Backups
Restoring just one file from a backup file takes an inordinately long time. About the third time that I needed to restore a single file, I decided to stop using backup software on my workstations. I need to back up only user data on the workstations, so I created a system of batch files to back up my workstation data across the network.

I run the backup from the target ( receiving) computer, which fetches backups from multiple workstations. The batch file runs automatically from Scheduled Tasks. Some workstations are both sending a backup to one computer and receiving a backup from another computer (a good paradigm for peer-to-peer networks). Each receiving computer has a folder named XXbackup ( substitute the name of the workstation being backed up for XX). Receiving computers that manage multiple computer backups have additional folders for YYbackup, ZZbackup, and so on. My backup batch file maps the shared drive on the sending computer, moves data files into the My Documents folder, then copies My Documents to the receiving computer. I arbitrarily decided on drive I for the mapped drive.

Figure 1 displays the commands in the batch file I created that backs up two of my computers. One computer, Admin, is used by a user named Kathy, and its C drive is shared as admin-c. It holds software data files that are stored in folders other than My Documents. The other computer, Apps, is used by a user named Sarah, and its C drive is shared as apps-c. The computer running the batch file (the receiving computer) has a separate folder for each computer's backup. Because I'm copying only My Documents, the batch file first takes care of the housework required to get everything I want to back up into the My Documents folder.

Notice that when the batch file is ready to copy My Documents, I turn to the Xcopy command, which has more powerful switches available than the Copy command does. For example, with Xcopy, I can create subdirectories on the fly on the receiving computer, so that whenever a user creates a new subdirectory in My Documents, it's copied correctly (the Windows Help files have detailed information on all command switches).

Of course, you can use the commands I discussed earlier to create a batch file on the local computer that moves data files stored outside of My Documents into the My Documents folder. Then, all you have to do is tell the user to run that batch file at the end of every day to make sure all data is included in the automated backup of My Documents. Even better, run the batch file automatically from Scheduled Tasks after the user's typical quitting time. (If you believe that leaving backups to users is a good idea, I have some land I'd like to sell you.) Another option is to write a backup batch file that backs up data files from their own folders, rather than moving data files into My Documents before backing up.

Batch File Power
As I mentioned at the beginning of this article, a batch file is merely a text file that contains DOS commands, one command to each line. You can add a great deal of power to your batch files by taking advantage of batch commands, a group of commands that exist to provide additional capabilities for batch files. These commands include programming-type commands such as If, If not, GoTo, For, and the ability to use variables (with the % character). I don't have the space to explain, or even list, all these tools, but you can learn how to use them in the Windows Help Files.

You can use a batch file to call a software application and include additional tasks. For example, some applications automatically save data in the application folder because that's where the user is located when the executable runs. If an application doesn't have a hard-coded data location, you can use a batch file to move the user's default location so that the data files are saved in that location. In the batch file, move to the location to which you want to locate the user, and call the application. The location can be a local folder (use the CD command), or a mapped drive. I've used this technique for in-house applications (but not a central database) that are used by individual employees. For example:

CD c:\mydata
c:\CustomerFiles\OurApp.exe

Or, to save the data in My Documents:

CD c:\"Documents and
         Settings"\%UserName%\"my
         documents"\MyCustomerData
c:\CustomerFiles\OurApp.exe

Incidentally, if the user logs into a domain, the variable for the username becomes %username%.%userdomain%, which is the way the name appears if you open the Documents and Settings folder (i.e., there's a period between the two variables).

To save the data on a server that's backed up:

net use z:\\ServerName\
   CustomerFiles\MyOwnFolder
z:
c:\CustomerFiles\OurApp.exe

You can also use a batch file to call an application, then automatically back up the data files, such as in the following example (which I've created for many home users).

When the user exits the program, the next line in the batch file executes (substitute the name of the data file for ).

c:\QUICKENW\qw.exe
Copy c:\quickenw\.*
  C:\"Documents and
  Settings"\%UserName%\"my
  documents"\QuickenBackup /y
Exit

This batch file assumes the user's backing up the My Documents folder every day.

Opening a Command Prompt from Any Folder
Often, I need to use a command prompt within a specific folder or subfolder. For example, if I have to rename a group of files in a folder, the command prompt is the only way to go (renaming through the GUI is an agonizing, one-at-a-time task). After you open the command prompt window, you have to navigate through the computer to get to the target folder. This is time-consuming, susceptible to typos, and generally annoying. It's easier to open a command prompt right at the target folder, using My Computer or Windows Explorer.

To add a command that opens a command window to the right-click menu of every folder, you have to edit the registry. Open the registry editor and take the following steps:

  1. Navigate to the HKEY_CLASSES_ ROOT\Directory\shell subkey.
  2. Create a new subkey and name it OpenNew.
  3. In the OpenNew subkey, open the Default item in the right pane, and make its value Open a Command Window. (This Registry value represents the phrase that appears on the shortcut menu, so you can substitute a phrase of your own.)
  4. Create a new subkey and name it Command under your new OpenNew subkey.
  5. Open the Default item in Command and enter cmd.exe /k cd %1 as the value. (You're only changing the value of the Default item; you're not adding a new data item to the subkey.)

After you make the registry changes, export the registry key HKEY_CLASSES_ROOT\Directory\shell\OpenNew. Windows saves the file with the extension .reg. Copy the .reg file to every other computer you work on and double-click its listing to add the key to each computer's registry. Now, no matter which computer you use, you can open a command window from any folder on the computer.

To add this command for a drive, use the same instructions, with two small changes:

  • Use the HKEY_CLASSES_ROOT\ Drive\shell subkey as the starting point.
  • The value of the Default item in the HKEY_CLASSES_ROOT\Drive\shell\ OpenNew\Command subkey is cmd .exe /k.

Windows PowerToys' Command Here program will perform these tasks for people who don't mind downloading software and also don't like working in the registry.

Customizing the Command Window
To customize the command prompt window, right-click the title bar and choose either Defaults or Properties. Regardless of which command you select, the resulting Properties dialog box shows the same tabs with the same choices. However, each option affects your system differently.

Changing the Defaults dialog box (Console Windows Properties, which Figure 2 shows) settings permanently changes the default settings for all command prompt windows. The changes you make aren't enabled in the current window, but you'll see them in windows you subsequently open. Changing the Properties dialog box ("C:\WINDOWS\System32\cmd.exe" Properties) settings changes the settings only for the current window, and the changes take effect immediately. However, after you modify this dialog box's settings and click OK, you can choose to make your changes permanent for any command prompt window you open from the same source. For example, if you used a specific shortcut (e.g., the Start menu shortcut or a desktop shortcut you created) to open a command prompt window and made changes in the "C:\ WINDOWS\System32\cmd.exe" Properties dialog box, those changes appear in the next command prompt window you open from the same shortcut icon. However, changes on a shortcut-by-shortcut basis are difficult to track, so if you know you want to change a Command Prompt window permanently, select the Default command.

The Console Windows Properties dialog box in Figure 2 displays four tabs. The choices are easy to understand, and each option has a "What's This?" Help file you can reach by right-clicking on the option name. Your new settings appear whenever you open a command prompt from the Accessories submenu. If you created a desktop or taskbar shortcut to a command window (I keep one on my Quick Launch toolbar), it may not use the new settings. In that case, delete the shortcut on your Quick Launch toolbar and copy it again from the Accessories submenu.

After you've designed the perfect command window, you can replicate it on other computers quite easily. Your changes were written to the registry, so all you have to do is export the registry subkey HKEY_ CURRENT_USER\Console. The export file is saved as a .reg file, and you should name the file appropriately (e.g., mycommandwindow.reg). Copy that file to your other computers. When you double-click the filename, Windows will ask you to confirm the fact that you want to merge this setting into the registry on the new machine.

Editing in the Command Prompt Window
You can copy (but not cut) text from a command prompt window. To copy text when you've enabled QuickEdit Mode (on the Options tab of either Properties dialog box I just discussed), drag your mouse to select text, then press Enter to place the text on the Clipboard. If you haven't enabled QuickEdit Mode, right-click the window's title bar, choose Edit from the drop-down menu, then select Mark. Drag your mouse to select the text, or position your cursor at the beginning of the text you want to copy and hold down the Shift key while you click the end of the selection. Press Enter to place the selected text on the Clipboard.

To paste text at a command prompt, position your cursor where you want to insert the text. If you've enabled QuickEdit Mode, right-click to automatically paste the text. If you haven't enabled QuickEdit Mode, right-click and select Paste from the pop-up menu. If you prefer to use the keyboard instead of a mouse, press Alt+Space, then press the letters E for enter and P for paste.

Spread Them Around—Your Batch Files Are Useful Everywhere
After you've become comfortable with the command line and creating batch files, you can use your knowledge (and your collected batch files) to make life easier for other users. In a peer-to-peer network, copy batch files that map drives or perform maintenance tasks to the other computers and teach other users how and when to use them. Your friends, neighbors, and relatives who ask for advice and help will also appreciate the delivery of a useful batch file. Send along a set of instructions for adding a batch file to the Task Scheduler.

Project Snapshot

PROBLEM: You want a more powerful way than the Windows GUI provides to perform some repetitive administrative tasks.

WHAT YOU NEED: Administrative permissions on your computer and your network; basic knowledge of folder structures

DIFFICULTY: 2 out of 5

PROJECT STEPS:

  1. Experiment with the batch file and batch command techniques in this article.
  2. Create batch files and batch commands to perform some of your administrative tasks.

Kathy Ivens (kivens@windowsitpro.com) is a senior contributing editor for Windows IT Pro. She has written more than four dozen books and hundreds of magazine articles about various computer subjects. Her latest book is Running QuickBooks in Nonprofits( CPA911 Publishing).