Mounting VHDs in Windows 7 from a command-line script
Windows 7 has native support for VHDs (virtual hard disks) built into the OS. VHDs are great for virtual machines, native VHD booting into recent Windows OSs, or even moving whole file systems around.
While you can mount VHDs from the Windows 7 diskmgmt.msc GUI, or via vhdmount, if you need support for mounting or unmounting VHDs from the command-line on a vanilla Windows 7 / Server 2008 install, you have to use diskpart.
diskpart’s mount commands are pretty simple:
C:\> diskpart DISKPART> sel vdisk file="[location of vhd]" DISKPART> attach vdisk
Unmounting is just as simple:
C:\> diskpart DISKPART> sel vdisk file="[location of vhd]" DISKPART> detach vdisk
These commands work fine on an ad-hoc basis, but I had the need to automate loading a VHD from a script. Luckily, diskpart takes a single parameter, /s, which specifies a diskpart “script”. The script is simply the command you would have typed in above:
C:\> diskpart /s [diskpart script file]
I’ve created two simple scripts, MountVHD.cmd and UnmountVHD.cmd that create a “diskpart script”, run it, then remove the temporary file. This way, you can simply run MountVHD.cmd and point it to your VHD:
C:\> MountVHD.cmd [location of vhd] [drive letter - optional]
Or unmount the same VHD:
C:\> UnMountVHD.cmd [location of vhd]
These files are hosted at Gist.Github if you want to use them or contribute changes.
Hi Nic. Thank you. I found very helpful. But there is a problem to assign drive letters. When I run – C: \> MountVHD.cmd xxxx.vhd H, the system assigns a drive letter to another, and still I get the window http://picsee.net/upload/2013-02-22/74830f3172a3.jpg you have any ideas to help me.
Strange, I haven’t seen this problem before. Do you see any errors in the Windows System or Application Event Log?
Is anything listed in regedit under HKLM\System\MountedDevices for H?
Nic, sorry for my bad English. This problem occurs only if Winodws7 virtual drive is not connected once. The first time you plug in the drive, the system installs the driver and possibly assign a drive letter itself. In Winodws 8, this is not a problem. I need to mount a virtual disk in WinPE 3.5. I’ve been looking for a solution and found your tool. Maybe you can help me write a script that requires a drive letter, but I don’t know how to do it. Thanks for the reply!