Hyper-V How To: Loopback Mount a VHD using Script

Some friends here on the Hyper-V team shared a PowerShell 2.0 script for loopback mounting a VHD, for example, if you need to use bcdedit to alter the boot configuration store offline:

# Loopback mount a VHD

param(
[string] $path = $(throw "Must supply a path"),
[string] $computer = "."
)

$ns = "root\virtualization"

# get the Msvm_ImageManagementService
$imageService = gwmi -Namespace $ns -ComputerName $computer Msvm_ImageManagementService

# mount the disk
$result = $imageService.Mount($path)
$ret = $result.ReturnValue

# handle the return parameter
if ($ret -eq 0)
{
# success. This should never actually be the return value on
# a successful mount. Instead it will return a job, which is
# associated with the mounted storage image.
# For completness, get the new mounted storage image.
$filter = "Name='$path'"
$filter = $filter.replace("\", "\\")
gwmi -Namespace $ns -ComputerName $computer Msvm_MountedStorageImage -filter $filter
}
elseif ($ret -eq 4096)
{
$job = [wmi]$result.Job
while ($job.jobstate -lt 7) {$job.Get()}
if ($job.JobState -eq 7)
{
# job succeeded. Get the associated Msvm_MountedStorageImage
gwmi -Namespace $ns -ComputerName $computer -query "associators of {$job}"
}
else
{
# job failed. Return its error code and description.
$job.ErrorCode
$job.ErrorDescription
}
}
else
{
# method failed. Return the failure code.
$ret
}

NOTE: If you use this - review the security recommendations at: https://support.microsoft.com/default.aspx/kb/954358

For more info on how to use PS cmdlets see: https://www.microsoft.com/technet/scriptcenter/topics/msh/cmdlets/index.mspx

See also James O’Neil’s New and improved PowerShell Library for Hyper-V. Now with more functions and... documentation!

For all 35 sample Hyper-V PS1 scripts in a zipfile, go to: Hyper-V PowerShell Example Scripts.zip-download