Recovering Virtual Machines in Hyper-V Server 2012 R2: Part 4

Summary: Use Windows PowerShell to import virtual machines that were not exported.

Hey, Scripting Guy! Question Hey, Scripting Guy! Over the weekend, I rebuilt our Hyper-V Server 2012 R2 environment. All of the machines and configuration data are on a second drive. I’d like to avoid spending all afternoon manually re-creating over 200 virtual machines in our lab. Is there an easier way?


Hey, Scripting Guy! Answer Hello SH,

Honorary Scripting Guy, Sean Kearney here—again filling in for our good friend Ed.

Note  This is the fourth post in a series. To review, see:

With Hyper-V and Windows PowerShell, life certainly got easier in Hyper-V Server 2012 and Hyper-V Server 2012 R2. We can now target an .xml file with the previous Hyper-V configuration (not just an exported one) and import it back into the environment.

Of course, we have to know where the file is. That’s why it was critical to build a list of the .xml files in Part 1 of this series. So we have a .csv file from Part 1 that we can access:

$HyperVlist=IMPORT-CSV C:HyperVList.csv

We can now target the XML data in each of these virtual machines to re-import them:

Foreach ($Machine in $HyperVList)


            IMPORT-VM –path $Machine.Name


But what if we forgot something? Maybe the hard disk for a machine was forgotten or is in the wrong location?

The cool part is Import-VM will catch that and spit out an error message that indicates to run Compare-VM against it. We can trap the virtual machines that didn’t import properly by grabbing the errors. We’ll actually report failures instead of successes so we know which virtual machines to re-examine.

Foreach ($Machine in $HyperVList)




            IMPORT-VM –path $Machine.Name –ErrorVariable BadVM | OUT-NULL

            If ($BADVM) { $Name=$Machine.Name; “Failure to import Machine $Name”)



You can then examine the virtual machines that failed by using Compare-VM as we did previously, but it might be something more detailed, such as the virtual machine exists already or that the VHDs are not in the expected location.

Tomorrow we’ll get those virtual machines running and adjust some useful settings that we typically need in a Hyper-V environment—all without the use of a GUI.

I invite you to follow the Scripting Guys on Twitter and Facebook. If you have any questions, send email to, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Sean Kearney, Honorary Scripting Guy and Windows PowerShell MVP