Apr 062010

Remember Reinhard Irnberger’s PUSHD trick to automatically map a drive if a UNC path is specified?
I use PUSHD “%~dp0” ever since, as the first command in any batch file that could be run from a UNC path.
Without this PUSHD command, the start/working directory of the batch file will be changed to %windir%\System32.

Today Denis St-Pierre informed me that this change of working directory also occurs when a batch file is running in elevated mode in Windows Vista, Windows Server 2008 or Windows 7.

I checked, and it occurs too when a script is started with RUNAS or PSEXEC.
I suppose that’s because my current/working directory is saved in my “volatile environment” in my profile, and thus is not available in the elevated user’s environment.

So there you have it, one more reason to specify (as opposed to assume) the working directory in your batch files.
I think PUSHD “%~dp0” is by far the most reliable way to do this, and it will work with RUNAS, PSEXEC, UNC paths, UAC and Explorer’s “Run as…” option.

Thanks Reinhard and Denis

Here is the Trick:
A great feature discovered by Reinhard Irnberger:

Sometimes it is necessary to get a Driveletter from a mapping.
Normally you will define a fixed Driveletter which you will map to your Remote path.
After you have done all things you will delete the drive mapping.

I found an simple solution for Windows Server 2003. Maybe it’s also working in Windows 2000.

With PUSHD \\Server\Share\[path] the system automatically creates a driveletter for you and jumps to it.
In the next step you can get the current Drive with %CD%.
When you use POPD you will jump back and the drivemapping is also deleted.

Attention: Because PUSHD can be nested you have to make sure that with POPD you don’t delete your current directory!

In my scripts I will use the following lines to Map a remote path:

PUSHD \\Server\Share\path
SET rmt=%CD%
CALL %rmt%\script.cmd

Wow! Great!
This works in Windows NT 4 (SP6a), 2000 and XP (Professional) too.

Thanks, Reinhard.