Skip to content

Instantly share code, notes, and snippets.

@tomfanning
Last active January 12, 2016 00:20
Show Gist options
  • Save tomfanning/c536aa6d1173e252e09e to your computer and use it in GitHub Desktop.
Save tomfanning/c536aa6d1173e252e09e to your computer and use it in GitHub Desktop.
PowerShell module for VM management
$ErrorActionPreference = "Stop"
# run like this:
# import-module vmtools.psm1
# move-vm -VmName "test-vm" -DestRoot "c:\HyperV"
function Move-VM {
[CmdletBinding()]
param (
[parameter(Mandatory=$true)] [string]$VmName,
[parameter(Mandatory=$true)] [string]$DestRoot
)
process {
$state_before = (get-vm $VmName).State
if ($state_before -ne "Off"){
stop-vm $vmname
}
#get all HDD paths
$hdinfo = Get-VMHardDiskDrive -vmname $vmname | select-object controllertype,controllernumber,controllerlocation,path
#remove HDDs from VM
Get-VMHardDiskDrive -vmname $vmname | Remove-VMHardDiskDrive
#export VM to new location
export-vm -name $vmname -path $destroot
#remove VM
remove-vm -name $vmname -force
$vmrootpath = join-path $destroot $vmname
$configpath = join-path $vmrootpath "Virtual Machines"
$vhdpath = join-path $vmrootpath "Virtual Hard Disks"
#import VM
import-vm -path (get-childitem $configpath -file).fullname
foreach ($hd in $hdinfo) {
$hdfilename = [system.io.path]::getfilename($hd.path)
$newhdpath = join-path $vhdpath $hdfilename
#move HDD to new location
move-item -path $hd.path -destination $newhdpath
#re-add HDD to VM in new location
Add-VMHardDiskDrive -vmname $vmname -controllertype $hd.controllertype -controllernumber $hd.controllernumber -controllerlocation $hd.controllerlocation -path $newhdpath
}
if ($state_before -eq "Running"){
start-vm $vmname
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment