Powershell and Hyper-V Management

 

There’s an awesome tool on codeplex for managing Hyper-V using Powershell called PSHyperV, it’s especially handy if you’re working with Hyper-V on a Windows Server Core installation.

http://pshyperv.codeplex.com/

Just download the library, drop the folder into the $pshome\modules directory, type import-module HyperV at a Powershell prompt and away you go…

 

This module adds some awesome cmdlets like New-VM, Start-VM, Stop-VM, Add-VMNewHardDisk, Add-VMNIC etc..

It has pretty much everything you need EXCEPT a way to change the default VHD path (C:\users\public …).  It will let you view the default path, just not change it.

Soooo, to remedy this we have to use WMI.   Below is a script I threw together that will allow you to change the default VHD path.

 

if(-not(Get-Module -name hyperv)){Import-Module hyperv}

$VMDRIVE= read-host “Please enter the drive letter to be used for Hyper-V VHD files (Do NOT include the colon :)”

if ($VMDRIVE.length -gt 1)

{

  write-host -foregroundcolor yellow “You provided too many characters, shortening the input to 1 letter.”

  $vmdrive = $vmdrive.substring(0,1)

}

if ($VMDrive -eq “C”)

{

  write-host -foregroundcolor yellow “The C drive should not be used for VHD files”

  exit

}

$test = test-path $vmdrive”:”

if ($test -ne “True” )

{

  Write-host -foregroundcolor Red “The drive letter provided does not exist on this system”

  exit

}

else

{

$query= get-wmiobject -class msvm_VirtualSystemManagementService -namespace “root\virtualization”

$querydata = get-wmiobject -class msvm_VirtualSystemManagementServiceSettingData -namespace “root\virtualization”

$querydata.DefaultExternalDataRoot = $VMDRIVE + “:\Hyper-V”

$querydata.DefaultVirtualHardDiskPath = $VMDRIVE + “:\Hyper-V”

$query.ModifyServiceSettings($querydata.psbase.gettext(1))

}

 

Obviously the bulk of the script is error-checking, making sure only a single letter was provided for the drive, that the drive provided exists and is not C.   The real meat of the script is the last 5 lines.

The script assumes a folder exists named Hyper-V in the root of the drive provided.