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

前端 未结 7 1290
无人及你
无人及你 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:46

    @longneck, I use something like this:

    for /f "tokens=2" %%i in ('net use * \\server\share') do (
        if defined netdrive goto :cont
        set netdrive=%%i
    )
    
    :cont
    echo.%netdrive% has been mapped
    pause
    
    net use %netdrive% /d /y
    pause
    

    This avoids the second call to net piped through find.

    You can also expand on this so that instead of calling set netdrive directly, you do it in a subroutine. This allows you to do more error checking or processing.

    for /f "tokens=2" %%i in ('net use * \\server\share') do (
        if defined netdrive goto :cont
        call :parse %%i
    )
    
    :parse
    if ~%1==%1~ goto :eof
    if Z:==%1 (
        set netdrive=%1
    )
    goto :eof
    
    :cont
    echo.%netdrive% has been mapped
    pause
    
    net use %netdrive% /d /y
    pause
    

    The parse subroutine here isn't terribly useful and only illustrates the concept.

提交回复
热议问题