Network Administration: Chaining Windows Commands

The ability to chain Windows commands together can let you accomplish in a single command what would otherwise take dozens of separate commands. You can enter two or more commands on the same line by separating the commands with an ampersand (&), like this:

C:>copy *.doc a: & del *.doc

Here, the Copy command copies all the .doc files to the A: drive. Then, the Del command deletes the .doc files.

Although that may be convenient, it’s also dangerous. What if the A: drive fills up so that all the files can’t be copied? In that case, the Del command executes anyway, deleting the files that didn’t get copied.

A safer alternative is to use two ampersands, which says to execute the second command only if the first command finishes successfully. Thus:

C:>copy *.doc a: && del *.doc

Now, the Del command will be executed only if the Copy command succeeds.

You can also use two pipe characters (the pipe is the vertical bar character that’s above the backslash on the keyboard) to execute the second command only if the first command fails. Thus,

C:>copy *.doc a: || echo Oops!

displays the message “Oops!” if the Copy command fails.

Finally, you can use parentheses to group commands. Then, you can use the other symbols in combination. For example:

C:>(copy *.doc a: && del *.doc) || echo Oops!

Here, the files are copied and then deleted if the copy was successful. If either command fails, the message is displayed.