How can I extract the drive letter for a new mapped drive in a .bat?
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.
And, for posterity, here's a rough template of how that all works out. Thanks again to @Snark, and @Neal.
Here's my original template, using pushd/popd.
@echo off :: Supply credentials for the NAS share. net use \\nasbox\sharename password /user:username /persistent:no :: Make sure it worked. if ERRORLEVEL 1 echo NET USE returned %ERRORLEVEL% && goto :EOF :: Use pushd to supply a drive letter for the share. pushd \\nasbox\sharename :: Copy the files to be backed up. Rinse and repeat. robocopy C:\path\to\important\stuff .\path\to\backups /MIR /Z :: Release the temporary drive letter. popd :: Optionally, revoke the credentials while the share's not in use. net use \\nasbox\sharename /delete
Note, that with my revelation from @Neal's comment, my specific application of pushd/popd are unnecessary here, and the form of the robocopy command simply changes to:
robocopy C:\path\to\important\stuff \\nasbox\sharename\path\to\backups /MIR /Z
No need to vote this up. Just wanted to have it here as a bread crumb for others who find this later.