How to unmount a VHD via command line in Windows 10

Since I haven't found a way to solely rely on MS-installed command line tools, I'll list third party solutions.


WinApiExec

WinApiExec enables the user to call the Windows API from the command line. The 32bit executable is only 3.5KB in size (x64: 5.5KB) and therefore ridiculously small, introducing as little overhead as probably possible.

winapiexec.exe virtdisk.dll@OpenVirtualDisk $a:2,0 "C:\Example Path\Test.vhd" 262144 0 0 $b:4 , virtdisk.dll@DetachVirtualDisk $$:7@0 0 0

vMount

vMount supports quite a few VHD-related functions. Its size (x86: 432KB; x64: 2.53MB) is rather huge for merely calling WinApi, so it's not a solution for my scenario, but might be useful to other people.

vmount detach \\.\PhysicalDriveX

DiskPart

For the sake of completeness DiskPart shall be mentioned, too. It supports a great deal of disk-related features, but has a rather sluggish way of going about it to automate the otherwise necessary user input for scripting purposes. It's also the only tool on the list that will be trapped in a loop if you accidentally run the script without elevated rights.

Save the following two lines into a text file:

select vdisk file="C:\Example Path\Test.vhd"
detach vdisk

Now, Dism can parse the text file as a form of unattended answer file:

DISKPART /s C:\Path_to\Name_Of_Textfile.txt

You can mount and unmount vhd/vhdx using native Windows 10 Powershell:

Import-module hyper-v
Dismount-VHD -Path 'c:\my.vhd'

From cmd/bat:

powershell -command "Import-module hyper-v; Dismount-VHD -Path 'c:\my.vhd'"

In either case you have to use elevated (Run as admin) prompt.

Another thing to note is that you need to enable Hyper-V feature first.


This is an expanded answer: (You should be able to glean how to umount VHD)

HowTo Automatically mount and umount VHD files on boot/shutdown.

Things seem to have changed a little in Windows 10.

First, I should say that I am mounting a VHD stored on a Linux File Server, mounting in over SMB.

Second, very important, is that if you don't detach the disk upon reboot, then when you try to re-attach it, it says "The file is in use and can't be accessed"..

So we need both automount and unmount. The unmount proved a bit tricker, since I cant just put it in startup folder. You have to use Group Policy. Also, when run as a "shutdown/startup" script, it ran to early, you need to run it at "Logon/Logoff"

I have 4 files in C:\mount

mount.cmd

@ECHO OFF

DISKPART /s C:\mount\mount.txt

umount.cmd

@ECHO OFF

DISKPART /s C:\mount\umount.txt

umount.txt

select vdisk file="\\192.168.1.255\Blizzard.vhdx"
detach vdisk

mount.txt

select vdisk file="\\192.168.1.255\Blizzard.vhdx"
attach vdisk

Now in start type/run gpedit.msc and add the scripts to logon/logoff

enter image description here