Doing more than one operation per line in a Windows batch file

Last Updated on December 5, 2015 by Dave Farquhar

Sometimes in a batch file I find myself needing to perform more than one operation on a server, especially inside a for loop. Rather than do a pair of for loops, which isn’t always desirable, you can use the & operator.

For example, if I’m deploying Java patches without the benefit of a tool like Shavlik Protect, I might do something like this:


Set serverlist=wb01 wb02 sql01 sql02
For %%i in (%serverlist%) do copy jdk-7u25-windows-x64.exe \\%%i\c$\temp

What if I want to delete the old file after copying over the new one? Well, instead of adding a second loop, I can do something like this:

Set serverlist=wb01 wb02 sql01 sql02
For %%i in (%serverlist%) do copy jdk-7u25-windows-x64.exe \\%%i\c$\temp & del \\%%i\c$\temp\jdk-7u17-windows-x64.exe

This is desirable because sometimes you want a second operation to happen right after a first, and can’t wait for two for loops to cycle all the way through. The project I’m working on currently has such a requirement. (It’s not pushing Java patches.)

And sometimes it’s desirable to only want to run the second command if the first was successful. For example, if a machine is down, there’s no point in trying to contact it twice. In that case, the && operator comes in:

Set serverlist=wb01 wb02 sql01 sql02
For %%i in (%serverlist%) do copy jdk-7u25-windows-x64.exe \\%%i\c$\temp && del \\%%i\c$\temp\jdk-7u17-windows-x64.exe

Sometimes this trick just serves to make a batch file shorter (whether it makes it easier to understand is debatable). And on rare occasions, it’s absolutely necessary for proper operation.

When I was in charge of patching a large Air Force command-and-control system that had enclaves on bases all over the world, sometimes over dodgy links, I used to do tricks like this, especially in conjunction with Robocopy, to copy huge patches like Oracle quarterly updates to each of our enclaves. Sometimes I would start the copies on Friday evening and they would finish sometime on Sunday.

But that combination of tricks saved me from having to come in and work over the weekend more than a few times.

If you found this post informative or helpful, please share it!