Auto-mount VHD image script for Windows 7

Mar 17, 2013

Support for mounting VHD images in Windows 7 is very useful, but unfortunately drives do not stay mounted after reboot. The following batch script can be used to auto-mount VHD images on Windows startup:

mount-disk.bat

@ECHO OFF

REM --------------------------------------------------------------------
REM This script mounts a VHD image "disk.vhd" from the current directory
REM To change the drive letter, set it manually (first time only)
REM --------------------------------------------------------------------

REM Configuration
REM -------------
SET VirtualDiskLocation="%CD%\disk.vhd"
SET DiskPartScriptLocation="%TEMP%\DiskMountScript-%RANDOM%.txt"

REM Write to the temporary script file
REM ----------------------------------
ECHO SELECT VDISK FILE=%VirtualDiskLocation% > %DiskPartScriptLocation%
ECHO ATTACH VDISK >> %DiskPartScriptLocation%

REM Execute the script
REM ------------------
ECHO Mounting %VirtualDiskLocation%...
DiskPart /s %DiskPartScriptLocation%

REM Cleanup
REM -------
DEL %DiskPartScriptLocation%

How to use the script

  1. Save the script as mount-disk.bat into the same directory as your .vhd image.
  2. Make sure your image is named disk.vhd (or edit the script to use a different filename)
  3. Create a shortcut to the mount-disk.bat and place it in the Windows Startup directory
Note: Startup directory for the current user is located at:
%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup

Changing the drive letter

  1. Mount the image
  2. Open the Run dialog box (Windows Key + R) and type diskmgmt.msc
  3. Right-click the mounted drive and click "Change Drive Letter and Paths..."
  4. Click "Change..." and select a new drive letter from the drop-down list
  5. Clicking "OK" will bring up a prompt - click "Yes" to confirm the change
Note: This needs to be done only once. Drive letter settings are persistent across reboots.

Dismounting the image

  1. Open the Run dialog box (Windows Key + R) and type diskmgmt.msc
  2. Locate the desired drive in the lower half of the window in the left column
  3. Open the right-click menu and select "Detach VHD"
  4. Click "OK" in the prompt to dismount the image
Careful: If you tick the "Delete the virtual hard disk file after removing the disk" check-box, your disk image file will be deleted.
comments powered by Disqus