Partager via


Manually import Hyper-V VMs

My VM's host system hard-drive crashed. Luckily most of my VMs are stored on separate drives so I should be able to recover them, I hoped. Not so fast, as you can only import VMs if they were previously exported. What to do? The best is to restore from exported VMs backed up somewhere. Or you can try the following.

Disclaimer: The following is not supported in any way. Try it on your own risk.

  1. See the excelent post on how to manually import VMs not previously exported.  Restrictions: It only works for Win2008, it does not work for R2.
  2. Use the following simple script to automate #1 - you'd see why if you have snapshots. Your VM including vhd and snapshots are in the folder pathtovm. Save the following script in importvm.cmd. Usage: importvm pathtovm. The script will generate vmiport.txt containing the commands you'll need to run to manually import your VM.

@echo off

@setlocal ENABLEEXTENSIONS

pushd .

for %%f in (%1"\Virtual Machines\*.xml") do (
    set vm=%%~nf
    @echo mklink "%systemdrive%\programdata\Microsoft\Windows\Hyper-V\Virtual Machines\%%~nf.xml" "%1\Virtual Machines\%%~nf.xml" >> vmimport.txt
    @echo icacls "%systemdrive%\programdata\Microsoft\Windows\Hyper-V\Virtual Machines\%%~nf.xml" /grant "NT VIRTUAL MACHINE\%%~nf":^(F^) /L >> vmimport.txt
    @echo icacls %1 /T /grant "NT VIRTUAL MACHINE\%%~nf":^(F^) >> vmimport.txt
    @echo rem >> vmimport.txt
)

for %%s in (%1"\Snapshots\*.xml") do (
    @echo mklink "%systemdrive%\ProgramData\Microsoft\Windows\Hyper-V\Snapshots\%%~ns.xml" "%1\Snapshots\%%~ns.xml" >> vmimport.txt
    @echo icacls "%systemdrive%\ProgramData\Microsoft\Windows\Hyper-V\Snapshots\%%~ns.xml" /grant "NT VIRTUAL MACHINE\%vm%":^(F^) /L >> vmimport.txt
    @echo rem >> vmimport.txt
)

popd

@endlocal