Pages

Friday, November 30, 2012

Running DOS Batch Files from a UNC Path


Sometimes it's the little things that get in the way of comfortable, quiet progress. I talked with a colleague today who is the architect of a couple of large Java-based applications. He asked me if I'd ever seen weirdness while running Java from a .bat file. Normally, if a Java app can be started from the command line, it should work from a bat file.

He was running a bat file to launch a new Java app. His particular annoyance was that, while it worked from his local machine, it failed when the bat file lived on a network share. He was getting the error "CMD does not support UNC paths as current directories." He didn't have a Java problem. He ran into a DOS CD command limitation. When the DOS shell starts up, it tries to set the current directory to the UNC path of the bat file before it runs the script. In this case, CD failed and the current directory was set to "C:\Windows" (it's a good thing his script didn't call 'del /s'!). The rest of the script failed because the Java classes were in the same directory as the bat file.

The solution is to use pushd at the beginning of the script. If the first line is 'pushd %~dp0', then pushd will map a drive to the UNC path and set the current directory there. Once the rest of the script has run, the last command must be 'popd', so the mapped drive is removed (otherwise, you'll continue to accumulate mapped drives to the UNC path until you run out of drive letters and then the script will fail).

Here's a simple example that just displays some messages and the contents of small.txt, another file in the same remote directory as the bat file:

@echo off
pushd %~dp0

echo.
echo.
echo I'm going to display the contents of small.txt:
type small.txt
echo.
echo.

popd
REM Keep the DOS shell open long enough to see the goodness of our script
SET /P foo=Press Enter to continue...


Create a file called 'small.txt' in the same directory as the batch file and its contents will be displayed when the script runs. Without the pushd/popd goodness, small.txt cannot be found.

Running the above code by double clicking the bat file from a window in Windows Explorer results in:

'\\fs\homes\foo'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported.  Defaulting to Windows directory.


I'm going to display the contents of small.txt:
This is a small amount of text.

Press Enter to continue...


Happy Computing.