4

OK, truth be told I already know the answer to the question. But, I scoured the net for quite some time on how to do this only to come up short. After piecing together several hints of semi-usable answers I found a couple of solutions that I would like to share for others who may have this same inquiry.

Craig
  • 627
  • 7
  • 14

1 Answers1

7

Solution #1 - PowerShell One-Liner... assumes the VHDX has but one volume and the desired mount location already exists in advance.

Mount-VHD -Path "C:\Temp\Test.vhdx" -NoDriveLetter -Passthru | Get-Disk | Get-Partition | where { ($_ | Get-Volume) -ne $Null } | Add-PartitionAccessPath -AccessPath "C:\Temp\MountPoint\"

The reason for the filter after Get-Partition is that I discovered that even though I only saw a single partition in disk manager when I created a VHDX file, there was actually a reserved partition that's not shown in disk manager. The filter removes the attempt to mount that partition.

Solution #2 - Assumes that your VHDX may (or may not) have multiple partitions and that you just want to easily identify each volume by drive number and partition number.

$MountPath = "C:\Temp\VHD\" # This folder must pre-exist
$VhdFile = "C:\Temp\Test.vhdx"
$MountedVhd = Mount-DiskImage -ImagePath $VhdFile -NoDriveLetter -PassThru | Get-Disk
$Partitions = $MountedVhd | Get-Partition

if (($Partitions | Get-Volume) -ne $Null) {
    $DriveNumberPath = $MountPath + "D" + $MountedVhd.Number
    New-Item $DriveNumberPath -ItemType "directory"
    foreach ($Partition in ($Partitions | where {($_ | Get-Volume) -ne $Null})) {
        $PartitionMountPath = $DriveNumberPath + "\P" + $Partition.PartitionNumber
        New-Item $PartitionMountPath -ItemType "directory"
        $Partition | Add-PartitionAccessPath -AccessPath $PartitionMountPath
    }
}

Alternatively, if you want to use the volume label for the partition as is shown in Disk Manager or File Explorer, you can substitute the $PartitionMountPath variable code as follows. Just be sure in advance that the volumes in fact have a name and that they are unique to the drive.

$PartitionMountPath = $DriveNumberPath + "\" + ($Partition | Get-Volume).FileSystemLabel

You could also wrap a portion of the Solution #2 code with a foreach loop and use a Get-ChildItem command to pull in multiple VHDX files from a folder location. It seemed a bit over the top to present that as a 3rd solution though.

Anyway... that's what I found for solutions. If you have a better/cleaner way... PLEASE let me know!

As to anyone wondering why I even wanted this in the first place... it was so I could throw this into a Task Scheduler job to auto-mount a VHDX file on boot. Solution #1 was all I really needed, #2 was just a bonus. ;)

Craig
  • 627
  • 7
  • 14