Monday, September 9, 2019

Windows batch file to map virtual drive letter with prompts and conditional branching

I created this batch file for NPS Maricopa Inc. to help colleagues map their local Dropbox root to a standard drive letter. This was necessary because AutoCAD Civil 3D data shortcuts do not use relative paths.

@echo off
SetLocal

set drive_letter=P

:get_action
  echo Virtual Drive Mapper
  echo Mapping to %drive_letter%:\
  echo.
  echo What do you want to do?
  echo.
  echo [S] Session (Map the drive until you restart Windows)
  echo [A] Add permanent (Map the drive until removed)
  echo [R] Remove permanent (Remove the permanent mapping)
  echo [N] Nothing
  echo.
  set /p answer=[S]ession, [A]dd permanent, [R]emove permanent, [N]othing: 
  if /i "%answer:~,1%" EQU "S" set action=session
  if /i "%answer:~,1%" EQU "A" set action=add
  if /i "%answer:~,1%" EQU "R" set action=remove
  if /i "%answer:~,1%" EQU "N" exit /b

  if /i "%answer:~,1%" EQU "S" goto get_folder
  if /i "%answer:~,1%" EQU "A" goto get_folder
  if /i "%answer:~,1%" EQU "R" goto remove_mapping

  echo.
  echo Please choose one of the given actions.
  goto get_action

:get_folder
  set /p dropbox_path=Please paste your Dropbox folder path here (e.g., C:\Dropbox): 
  if {%dropbox_path%}=={} goto get_folder
  goto test_folder_exist
  
:test_folder_exist
  if exist %dropbox_path% (
    goto create_command
  ) else (
    echo That path does not exist. Please try again.
    goto get_folder
  )

:create_command  
  set map_command=subst %drive_letter%: "%dropbox_path%"
  goto map_drive_%action%


:map_drive_session
  %map_command%
  goto end_file

:map_drive_add
  %map_command%
@echo on
  REG ADD "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v "NPS Maricopa Dropbox Drive" /t REG_SZ /d "subst %drive_letter%: \"%dropbox_path%\"" /f
@echo off
  goto end_file

:map_drive_remove
  REG DELETE "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v /f
  goto end_file

:end_file
  pause
  EXIT
EndLocal

No comments: