18 April 2013

Manipulating vhd and vhdx with powershell

Everything you want to know about how to create,convert, re-size, mount and attach Hyper-V disks.

The Hyper-V management gui provides great simple to use tools for basic virtual disk manipulation, if however you want to get serious you break out the powershell cmdlets.

Creating a virtual disk
To start things off I will creat a new dynamic disk that is 25GB in size.

New-VHD -Path 'b:\test.vhdx' -Dynamic -SizeBytes 25GB 

To check the properties of the disk as we progress we will keep referring to

Get-VHD .\test.vhdx

After the initial creation we will see


ComputerName            : ET-LAB-HV03
Path                    : B:\test.vhdx
VhdFormat               : VHDX
VhdType                 : Dynamic
FileSize                : 4194304
Size                    : 26843545600
MinimumSize             : 
LogicalSectorSize       : 512
PhysicalSectorSize      : 4096
BlockSize               : 33554432
ParentPath              : 
FragmentationPercentage : 0
Alignment               : 1
Attached                : False
DiskNumber              : 
IsDeleted               : False
Number                  : 

Converting between vhd and vhdx
The only  thing you need to specify is the extention, the correct type is used.

Convert-VHD .\test.vhdx -DestinationPath .\testFixed.vhd

Converting between dynamic and Fixed
This is controlled by the -VHDType parameter

Convert-VHD .\test.vhdx -VHDType Fixed -DestinationPath .\testFixed.vhdx

Attaching a VHD to a virtual machine

Add-VMHardDiskDrive -VMName TestVM -Path B:\test.vhdx

Mounting a virtual disk to a physical host
Server 2012 introduced to feature of being able to mount a vhd as a disk form the OS.

mount-vhd .\test.vhdx 

The disk will now appear as a disk to the operating system.   Since created the disk but no partitions there is no associated volume.

Initialize the disk

Initialize-Disk -Number 1

Create the partition

New-Partition -DiskNumber 1 -DriveLetter j -Size 10GB

Create the volume

Format-Volume -DriveLetter j -FileSystem ReFS

Now that we have a volume on the disk we have a new attribute.  if your run get-vhd now you will see a value for  minimumsize

Un-mount the virtual disk

Dismount-VHD -DiskNumber 1

Re-size the fixed disk to a certain size
The vhd can only be as small as the minimumsize (Volume size) but it can be bigger

To shrink or grow the file to a predefined size use

Resize-VHD .\testfixed.vhdx -SizeBytes 15GB

Or to make it is small as possible use

Resize-VHD .\testfixed.vhdx -ToMinimumSize

Conclusion
Using powershell allows you to create and manage virtual disks at all it's life stages.  It also provides more functionality that you have using the GUI tools and allows you to break away from predefined default size restrictions.

No comments:

Post a Comment