2

My use case is the following: I have a ready vhd image and need to mount it to a path f.e. D:\vhd\active. At the moment my solution is a combination of Powershell Hyper-V and diskpart commands but this seems very dirty and hacked:

Mount-VHD -Path D:\vhd-file.vhd -NoDriveLetter 
diskpart> select vdisk file="D:\vhd-file.vhd"
diskpart> sel par 1
diskpart> assign mount="D:\vhd\active

As you can see I've used the "NoDriveLetter" because I don't want auto assign. The "sel par 1" I have to do because I found no easier way to select the right volume (other ideas were to check "lis vol" before the Mount-VHD and after it ... but yeah I always only have one partition so "sel par" ftw!)

I found the Microsoft Dev VHD Reference and could "Open" and "Attach" the VHD image via C# pinvoke code. I could even initialize it with a combination of CreateFile from kernel32.dll and DeviceIoControl with CREATE_DISK parameters. But I found no way to mount it to the folder path. I tried SetVolumeMountPoint and GetVolumeNameForVolumeMountPoint from kernel32.dll but the Guid of my VHD or the VirtualDiskIdentifier doesn't seem to be the right parameters for these functions.

My question is if someone can point me to the right functions/methods to achieve the same result like I have with the scripted solution but in code. In code means C/C++ or C# ... I am able to write my own C#-Wrappers if it is easier to do this task in plain C or C++.

seveves
  • 1,282
  • 4
  • 17
  • 37

1 Answers1

0

SetVolumeMountPoint() would require a mounted volume's GUID; VirtualDiskIdentifier won't work here as it is relative to the disk.

One way to get around this would be to run FindFirstVolume/FindNextVolume loop twice. Once, before the mount and once immediately after the mount. The diff between the 2 results should give you the mounted volume's GUID.

Also, if you are creating GPT based virtual disk, then you could directly pass the "Unique partition GUID" which is embedded inside the GPT partition table entry of the vhd file that you are trying to mount. Meaning: on Windows, after a GPT disk mounts, the resulting volume(s) GUID is same as the one embedded inside the respective GPT partition table entry of the VHD/LUN. See the below image. For that, you'd have to read few raw VHD file blocks and do some parsing. mountvol output - embedded PTE unique GUID comparision

Neelabh Mam
  • 300
  • 6
  • 10
  • Perhaps you could edit this to make it more readable. There is formatting help available. – Sid Jan 27 '18 at 12:04