@ECHO OFF :: TempNWD.bat, Version 1.00 for Windows NT :: Map a network drive temporarily, and only if necessary :: Written by Rob van der Woude :: http://www.robvanderwoude.com :: Initialize variables SET EXISTDRV= SET UNC=%1 SET SWITCH=%2 IF NOT [%SWITCH%]==[] SET SWITCH=%SWITCH:~0,2% IF NOT [%SWITCH%]==[] IF /I NOT [%SWITCH%]==[/D] GOTO Syntax :: Check for forbidden third parameter IF NOT [%3]==[] GOTO Syntax :: Check if first parameter is empty IF [%UNC%]==[] GOTO Syntax :: Check for 2 leading backslashes IF NOT %UNC:~0,2%==\\ GOTO Syntax :: Parse parameter into \\server\share FOR /F "tokens=1,2* delims=\" %%A IN ('ECHO.%UNC%') DO ( SET SERVER=%%A SET SHARE=%%B SET DUMMY=%%C ) :: Check parsed parameter IF [%SHARE%]==[] GOTO Syntax IF NOT [%DUMMY%]==[] GOTO Syntax :: Check if server is on-line PING %SERVER% | FIND "TTL=" >NUL IF ERRORLEVEL 1 GOTO OffLine :: Check if share exists DIR \\%SERVER%\%SHARE% >NUL 2>NUL IF ERRORLEVEL 1 GOTO NoShare :: Check optional second parameter (/D) IF /I [%SWITCH%]==[/D] GOTO Delete :: Check if a mapping to the specified UNC exists FOR /F "tokens=2 delims= " %%A IN ('NET USE ^| FIND /I "\\%SERVER%\%SHARE%"') DO ( SET EXISTDRV=%%A SET MAPPEDDRV=%%A ECHO Drive %%A already mapped ) IF [%EXISTDRV%]==[] FOR /F "tokens=2 delims= " %%A IN ('NET USE * \\%SERVER%\%SHARE% /PERSISTENT:NO ^| FIND "Drive"') DO ( SET MAPPEDDRV=%%A ECHO Drive %%A is now mapped ) %MAPPEDDRV% GOTO End :Delete :: Remove mapping IF [%EXISTDRV%]==[] ( IF [%MAPPEDDRV%]==[] ( ECHO No drive mapping found to remove ) ELSE ( %SystemDrive% NET USE %MAPPEDDRV% /D ) ) ELSE ( ECHO Skipped removal of existing drive %EXISTDRV% mapping ) GOTO End :NoShare ECHO. ECHO Share name invalid or no access to share GOTO Syntax2 :OffLine ECHO. ECHO Server name invalid or server is off-line GOTO Syntax2 :Syntax ECHO. ECHO TempNwD.bat, Version 1.00 for Windows NT ECHO Map a network drive temporarily, if necessary. ECHO. ECHO Written by Rob van der Woude ECHO http://www.robvanderwoude.com :Syntax2 ECHO. ECHO Usage: %~n0 \\server\share [ /D[elete] ] ECHO. ECHO If a drive mapping to the specified UNC already exists, then that drive ECHO mapping is used. ECHO Used with the /D switch, an existing drive mapping will not be removed, ECHO only mappings created by this batch file can be removed by this batch ECHO file. ECHO. ECHO Example of usage (assuming yourprog.exe is located in \\server\share\): ECHO. ECHO @echo off ECHO call %~n0 \\server\share ECHO yourprog.exe ECHO call %~n0 \\server\share /D :End