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

set drive_letter=P

  echo Virtual Drive Mapper
  echo Mapping to %drive_letter%:\
  echo What do you want to do?
  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
  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 Please choose one of the given actions.
  goto get_action

  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
  if exist %dropbox_path% (
    goto create_command
  ) else (
    echo That path does not exist. Please try again.
    goto get_folder

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

  goto end_file

@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

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


No comments: