Tuesday, October 20, 2009

How to mount disk to specific drive letter

The problem
Pre: for sure, we'll talk about lovely Windows cause in Linux even the meaning of the word "problem" differs..
So, you have a removable disk (flash or hard drive) and when you plug it into your Windows PC it appears with different drive letters. For example, you have a bunch of media on a flash drive. You plug it for the first time, Windows provides drive letter "G" for this drive. Then you import all media into some media library. After a while you pull out flash and later plug it again. Now Windows decides to name this drive letter with "F" and.. you can't access your media files from the media library. On my own PC this happens not so frequently but each time I have to refresh my media library in Foobar 2000 player. So boring!
The day has come to say "NO"!


The solution
I've done simple script which automatically mounts disk to the drive letter you want to. I dislike writing tricky bat-files, and I also wondering in Groovy, that it to say, my auto-mount feature requires Java and Groovy installed. You can read a small how-to-configure-environment-guide. The script below should be run after the needed disk has been plugged, i.e., after the Windows has mounted the disk. Another requirement is to pre-define disk label.
def NEEDED_DRIVE_LETTER = 'B'
def DISK_LABEL_TO_SEARCH = 'STORAGE'


def txt = 'cmd /c mountvol'.execute().text
def m = []
txt.split('[\\r\\n]+').each {m << it.trim()}

def volumeId
def disk
m.eachWithIndex() { obj, i -> 
  if (obj.endsWith(':\\')) {
    txt = "cmd /c vol ${obj - '\\'}".execute().text
    if (txt.contains(" is $DISK_LABEL_TO_SEARCH")) {
      volumeId = m[i - 1]
      disk = obj
    }
  }
}


if (!(NEEDED_DRIVE_LETTER + ':\\').equalsIgnoreCase(disk)) {
  "cmd /c mountvol $disk /d".execute()
  "cmd /c mountvol $NEEDED_DRIVE_LETTER: $volumeId".execute()
}

Two points to customize in this script are right are:
NEEDED_DRIVE_LETTER - drive letter where you want to mount your disk
DISK_LABEL_TO_SEARCH - disk label of your disk


P.S. Please don't blame my groovy karma - I'm a youngster in this field. Anyway, every comment is welcome!

No comments:

Post a Comment