Mapping a network drive without hardcoding a drive

2019-01-17 22:05发布

I need to map a network drive with a batch file, but don't want to specify the drive letter.

The batch file is used as part of a deployment process; I call the batch file from CruiseControl.Net, the batch file needs to map a UNC path which requires credentials to authenticate. Then the batch file calls RoboCopy to deploy the website from the output directory to the destination (and excludes some files and folders). Finally the batch deletes the network drive.

The problem is that this isn't scalable, it's fine when there are only a few projects but we've now got 20 projects using this approach and are running out of drive letters to map. I don't want to re-use drive letters as they could collide - which would be bad.

This is an example of the batch file:

@echo off
net use x: \\192.168.0.1\Share\wwwroot\MyProject /user:mydomain\myuser MyP455w0rd
robocopy.exe "W:\wwwroot\MyProject" x:\ *.* /E /XO /XD "App_Data/Search" "*.svn" /XF "sitefinity.log" "Thumbs.db" /NDL /NC /NP
net use x: /delete

and formatted for readability:

@echo off
net use x: \\192.168.0.1\Share\wwwroot\MyProject 
    /user:mydomain\myuser MyP455w0rd
robocopy.exe "W:\wwwroot\MyProject" x:\ *.* /E /XO /XD 
    "App_Data/Search" "*.svn" /XF "sitefinity.log" "Thumbs.db" /NDL /NC /NP
net use x: /delete

7条回答
闹够了就滚
2楼-- · 2019-01-17 22:52

A possible solution is to apply the pushd command to a UNC path that exists for sure, so a temporary drive letter is created that points to that path. The current directory, namely the root of the temporary drive, can be determined to get the drive letter. Finally, the popd command must be used to delete the temporary drive letter:

pushd "\\%COMPUTERNAME%\ADMIN$"
rem /* Do stuff here with the root of the temporarily created drive
rem    used as the current working directory... */
rem // Store the current drive in variable `DRIVE` for later use:
for /F "delims=:" %%D in ("%CD%") do set "DRIVE=%%D:"
popd
echo The next free drive letter is `%DRIVE%`.

The variable COMPUTERNAME and the share \\%COMPUTERNAME%\ADMIN$ should exist on all modern (NT-based) Windows systems.


If you do not want the current environment to become even temporarily "polluted" by the attempt of pushd to derive a free drive letter, you may want to use the following approach:

for /F "delims=:" %%D in ('
    pushd "\\%COMPUTERNAME%\ADMIN$" ^& ^
        for %%Z in ^(.^) do popd
') do set "DRIVE=%%D:"
echo The next free drive letter is `%DRIVE%`.
查看更多
登录 后发表回答