Re-Import VMs into Hyper-V

toolsNormaly you can only import a Virtual Machine (VM) into Hyper-V if you have exported it. If you lose your Hyper-V settings or have to import it into a new Hyper-V Server in case of a desaster recovery than you can use the steps descripted in this (and other) blog post: http://blogs.msdn.com/b/robertvi/archive/2008/12/19/howto-manually-add-a-vm-configuration-to-hyper-v.aspx

The problem is that you have to handle many long pathes and cryptical GUIDs. I had to do that for a bunch of different VMs and being chronical lacy I created three batch files for it:

  1. importVM.cmd “GUID” “Path to Virtual Machine” creates the link and corrects the permissions on the link and the vm folder
  2. importSnapshot.cmd “SnapshotGuid” “VMGuid” “Path to Snapshot” creates the snapshot link and the right permission.

Not very impressiv? Well, the third batch files combines this two scripts:

  1. addMachine.cmd: Takes the basis path (the path where the sub-folder Virtual Machine, Snapshots exists) and extracts the VM-GUID, all Snapshots-GUIDs and the other pathes to automaticly create the links and permissions.

So with one simple command (addMachine.cmd C:\ClusterStorage\Volume4\VM1) you can import the complete VM.

— addMachine.cmd ——

setlocal ENABLEDELAYEDEXPANSION

set vmBasisPath=%~1

for /f %%a in ('dir "%vmBasisPath%\Virtual Machines\" /b /ad') do (
  set guid=%%a
)

echo %guid%
call "%~dp0importVM.cmd" %guid% "%vmBasisPath%"

for /f %%a in ('dir "%vmBasisPath%\Snapshots\" /b /ad') do (
  call "%~dp0importSnapshot.cmd" %%a %guid% "%vmBasisPath%\Snapshots"
)

endlocal

——————————–

— importVM.cmd ———-

setlocal

set guid=%~1
set vmPath=%~2
set xmlPath=%vmpath%\Virtual Machines\%guid%.xml

mklink "c:\ProgramData\Microsoft\Windows\Hyper-V\Virtual Machines\%guid%.xml" "%xmlpath%"

Icacls "c:\ProgramData\Microsoft\Windows\Hyper-V\Virtual Machines\%guid%.xml" /grant "NT VIRTUAL MACHINE\%GUID%":(F) /L
Icacls "%vmpath%" /grant "NT VIRTUAL MACHINE\%GUID%":(F) /T

Endlocal

——————————–

— importSnapshot.cmd —

setlocal

set guid=%~1
set vmguid=%~2

rem C:\ClusterStorage\Volume4\mcFly2\Snapshots
set snapPath=%~3

if not EXIST "%snapPath%\%guid%.xml" goto ende

Mklink "C:\ProgramData\Microsoft\Windows\Hyper-V\Snapshots\%guid%.xml" "%snapPath%\%guid%.xml"
Icacls C:\ProgramData\Microsoft\Windows\Hyper-V\Snapshots\%guid%.xml /grant "NT VIRTUAL MACHINE\%vmguid%":(F) /L

:ende
Endlocal

———————————

This entry was posted in English, Hyper-V, Tools and tagged , , , , . Bookmark the permalink.