Q. How can I mount a Virtual Hard Disk (VHD) in Hyper-V without additional programs?
October 22, 2008
A. Hyper-V comes with a complete Image Management Service that can be called from scripts, programs, and code to perform mount and unmount operations. Microsoft has provided a script to mount VHD files here and a script to unmount them here.
You can actually create much simpler scripts than Microsoft’s, as I’ve done here. These Windows Management Instrumentation (WMI) scripts are not as fully featured as Microsoft’s, but they do the job. You can also download the scripts in a zip file right here.
Save the mounting script below as vhdmount.vbs.
Option Explicit
Dim objWMIService, objVHDService, strComputer, strVHDFile
strComputer ="."
' Check all arguments required have been passed
If Wscript.Arguments.Count < 1 Then
Wscript.Echo "Arguments required. For example:" & vbCrLf &
"cscript vhdmount.vbs disk.vhd"
Wscript.Quit(0)
End If
strVHDFile = Wscript.Arguments(0)
Set objWMIService = GetObject("winmgmts:\" & strComputer &
"rootvirtualization")
Set objVHDService = objWMIService.ExecQuery("SELECT * FROM
Msvm_ImageManagementService").ItemIndex(0)
objVHDService.Mount(strVHDFile)
(Note that there are several lines in this script that had line breaks inserted for publication. Make sure to remove them if saving the text as a script, or just download the scripts from this article as a zip file.)
Ensure that the VHD is not in use by a virtual machine when you run the commands. You can mount the VHD by using the following command:
D:projectsVBScripts>cscript vhdmount.vbs d:virtualsdemo1demo1.vhd
You then need to bring the disk online using the Microsoft Management Console (MMC) Disk Management snap-in. After you’ve done so, a drive letter will be associated with the disk, as the following screenshot shows:
You can unmount the VHD by using the following script. Save it as vhdunmount.vbs.
Option Explicit
Dim objWMIService, objVHDService, strComputer, strVHDFile
strComputer ="."
' Check all arguments required have been passed
If Wscript.Arguments.Count < 1 Then
Wscript.Echo "Arguments required. For example:" & vbCrLf &
"cscript vhdmount.vbs disk.vhd"
Wscript.Quit(0)
End If
strVHDFile = Wscript.Arguments(0)
Set objWMIService = GetObject("winmgmts:\" & strComputer &
"rootvirtualization")
Set objVHDService = objWMIService.ExecQuery("SELECT * FROM
Msvm_ImageManagementService").ItemIndex(0)
objVHDService.Unmount(strVHDFile)
(Note that there are several lines in this script that had line breaks inserted for publication. Make sure to remove them if saving the text as a script, or just download the scripts from this article as a zip file.)
To run the script and unmount the VHD, run the following command:
D:projectsVBScripts>cscript vhdunmount.vbs d:virtualsdemo1demo1.vhd
About the Author
You May Also Like