Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for tempnwd2.bat

(view source code of tempnwd2.bat as plain text)

  1. @ECHO OFF
  2. :: TempNWD.bat,  Version 2.00 for Windows NT
  3. :: Map a network drive temporarily, and only if necessary
  4. :: Written by Rob van der Woude
  5. :: http://www.robvanderwoude.com
  6.  
  7. :: Initialize variables
  8. SET EXISTDRV=
  9. SET UNC=%1
  10. SET SWITCH=%2
  11. IF NOT [%SWITCH%]==[] SET SWITCH=%SWITCH:~0,2%
  12. IF NOT [%SWITCH%]==[] IF /I NOT [%SWITCH%]==[/D] GOTO Syntax
  13. :: Check for forbidden third parameter
  14. IF NOT [%3]==[] GOTO Syntax
  15. :: Check if first parameter is empty
  16. IF [%UNC%]==[] GOTO Syntax
  17. :: Check for 2 leading backslashes
  18. IF NOT %UNC:~0,2%==\\ GOTO Syntax
  19. :: Parse parameter into \\server\share
  20. FOR /F "tokens=1,2* delims=\" %%A IN ('ECHO.%UNC%') DO (
  21. 	SET SERVER=%%A
  22. 	SET SHARE=%%B
  23. 	SET DIR=%%C
  24. )
  25. :: Check parsed parameter
  26. IF [%SHARE%]==[] GOTO Syntax
  27. :: Check if server is on-line
  28. PING %SERVER% | FIND "TTL=" >NUL
  29. IF ERRORLEVEL 1 GOTO OffLine
  30. :: Check if share exists
  31. DIR \\%SERVER%\%SHARE% >NUL 2>&1
  32. IF ERRORLEVEL 1 GOTO NoShare
  33.  
  34. :: Check if a mapping to the specified UNC exists
  35. FOR /F "tokens=2 delims= " %%A IN ('NET USE ^| FIND /I "\\%SERVER%\%SHARE%"') DO (
  36. 	SET EXISTDRV=%%A
  37. 	ECHO Drive %%A already mapped
  38. )
  39. IF "%SWITCH%"=="" IF [%EXISTDRV%]==[] (
  40. 	PUSHD \\%SERVER%\%SHARE%\%DIR%
  41. ) ELSE (
  42. 	PUSHD %EXISTDRV%\%DIR%
  43. )
  44. IF /I "%SWITCH%"=="/D" (
  45. 	POPD
  46. 	IF NOT [%EXISTDRV%]==[] NET USE %EXISTDRV% /D
  47. )
  48. GOTO End
  49.  
  50. :NoShare
  51. ECHO.
  52. ECHO Share name invalid or no access to share
  53. GOTO Syntax2
  54.  
  55. :OffLine
  56. ECHO.
  57. ECHO Server name invalid or server is off-line
  58. GOTO Syntax2
  59.  
  60. :Syntax
  61. ECHO.
  62. ECHO TempNwD.bat,  Version 2.00 for Windows NT
  63. ECHO Map a network drive temporarily, if necessary.
  64. ECHO.
  65. ECHO Written by Rob van der Woude
  66. ECHO http://www.robvanderwoude.com
  67.  
  68. :Syntax2
  69. ECHO.
  70. ECHO Usage:  %~n0  \\server\share[\dir]
  71. ECHO.
  72. ECHO If a drive mapping to the specified UNC already exists, then that drive
  73. ECHO mapping is used.
  74. ECHO.
  75. ECHO Example of usage (assuming yourprog.exe is located in \\server\share\mydir):
  76. ECHO.
  77. ECHO     @echo off
  78. ECHO     call %~n0 \\server\share\mydir
  79. ECHO     yourprog.exe
  80. ECHO     call %~n0 \\server\share\mydir /D
  81.  
  82. :End
  83.  

page last modified: 2024-04-16; loaded in 0.0073 seconds