Command Line – Extract Drive Letter for New Mapped Drive in .bat

backupcommand linenetwork-shares

I'm creating a simple command-line backup script to use robocopy to mirror "important" stuff to my NAS box. I would prefer not to rely on a hard-coded mapped drive letter for that NAS box. In the script I would like to map a temporary drive letter, copy the relevant files, and dispose of the mapped drive. I don't want to assume that if that drive letter is already mapped, that it's pointing to the place I expect. I also don't want to "assume" that some drive letter is available when I map the drive, thus the leading '*'.

    net use * \\nasbox\sharename password /user:username /persistent:no

What's the proper way within my .bat script to extract that drive letter for use in subsequent commands? I was thinking that I could piece together some variant of "for"'s token-parsing, but I also suspect there must be an easier way than esoteric for-syntax.

    C:\>net use * \\nasbox\sharename password /user:username /persistent:no
    Drive Z: is now connected to \\nasbox\sharename.

    The command completed successfully.


    C:\>

Once I have the mapped drive letter, I would like to follow up with commands along the lines of:

    robocopy C:\path\to\important\stuff %NewDrive%\path\to\backup /MIR /Z

Best Answer

Use the commands pushd and popd.

pushd \\server\share will create a temporary drive (starting from Z: and going backwards till it finds an available letter) and go into it. When you're done, popd will delete the temporary drive and get you back where you were.

C:\Users\Snark>pushd /?
Stores the current directory for use by the POPD command, then
changes to the specified directory.

PUSHD [path | ..]

  path        Specifies the directory to make the current directory.

If Command Extensions are enabled the PUSHD command accepts
network paths in addition to the normal drive letter and path.
If a network path is specified, PUSHD will create a temporary
drive letter that points to that specified network resource and
then change the current drive and directory, using the newly
defined drive letter.  Temporary drive letters are allocated from
Z: on down, using the first unused drive letter found.

C:\Users\Snark>popd /?
Changes to the directory stored by the PUSHD command.

POPD


If Command Extensions are enabled the POPD command will delete
any temporary drive letter created by PUSHD when you POPD that
drive off the pushed directory stack.
Related Question