Mapping a network drive without hardcoding a drive letter in a batch file

前端 未结 7 1298
无人及你
无人及你 2020-12-05 19:24

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 batc

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 19:47

    Simplest method:

    pushd "\\server\share\wwwroot\My Project"
    robocopy . x:\ *.* /E ...etc
    popd
    

    Pushd will automatically map a network drive to an available letter, and popd will remove it. They are internal CMD commands; using UNC paths requires extensions enabled. Batch example:

    @echo off
    pushd %1
      echo. --- Processing %1 as "%cd%"
      echo. ...
      rem do thing here
      echo. Done.
    popd
    

    Note: in this implementation using a command line argument, the path on command line must be quoted.

    Sample session:

    E:\temp>.\demo-pushd.bat "\\server\share\wwwroot\My Project"
     --- Processing "\\server\share\wwwroot\My Project" as "X:\wwwroot\My Project"
        ...
        Done.
    
    E:\temp> net use X:
    The network connection could not be found.
    
    More help is available by typing NET HELPMSG 2250.
    E:\temp>
    

提交回复
热议问题