Windows 7 has some nice and very welcome functionality for attaching/detaching VHD files so that you can access files in them directly from the operating system, which is something I’ve been finding very useful when working out of my laptop. Unfortunately, it’s a bit of a drag to have to go through disk manager every time I want to use one of my VHD files.

I started looking for a way to do this from the command line and discovered that diskpart.exe can do it, but the syntax is more than I can usually remember, so I just wrote these two quick PowerShell functions:

function add-vhd($vhdfile) {
$path = resolve-path $vhdfile
$script = "SELECT VDISK FILE=`"$path`"`r`nATTACH VDISK"
$script | diskpart
}
function remove-vhd($vhdfile) {
$path = resolve-path $vhdfile
$script = "SELECT VDISK FILE=`"$path`"`r`nDETACH VDISK"
$script | diskpart
}


Tomas Restrepo

Software developer located in Colombia. Sr. PFE at Microsoft.