Share via


Importing Virtual Machines

The following C# and VBScript samples import a virtual machine (VM).

C#: The referenced utilities can be found in Common Utilities for the Virtualization Samples.

using System;
using System.IO;
using System.Management;

namespace HyperVSamples
{
    class ImportVirtualSystemExMoreGranularClass
    {

        static ManagementObject CreateSwitch(ManagementScope scope, string name, string friendlyName, int learnableAddress)
        {            
            ManagementObject switchService = Utility.GetServiceObject(scope, "Msvm_VirtualSwitchManagementService");
            ManagementObject createdSwitch = null;

            ManagementBaseObject inParams = switchService.GetMethodParameters("CreateSwitch");
            inParams["FriendlyName"] = friendlyName;
            inParams["Name"] = name;
            inParams["NumLearnableAddresses"] = learnableAddress;
            inParams["ScopeofResidence"] = null;
            ManagementBaseObject outParams = switchService.InvokeMethod("CreateSwitch", inParams, null);
            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                Console.WriteLine("{0} was created successfully", inParams["Name"]);
                createdSwitch = new ManagementObject(outParams["CreatedVirtualSwitch"].ToString());
            }
            else
            {
                Console.WriteLine("Failed to create {0} switch.", inParams["Name"]);
            }
            return createdSwitch;
        }
        

        static ManagementBaseObject GetVirtualSystemImportSettingData(ManagementScope scope, string importDirectory, string rootDirectoryToCopy)
        {
            string targetVhdResourcePath = importDirectory + "\\Temp.vhd"; //Directories specified should exist
            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");
            ManagementBaseObject importSettingData = null;
            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("GetVirtualSystemImportSettingData");
            inParams["ImportDirectory"] = importDirectory;

            ManagementBaseObject outParams = virtualSystemService.InvokeMethod("GetVirtualSystemImportSettingData", inParams, null);

            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    importSettingData = (ManagementBaseObject)outParams["ImportSettingData"];
                    Console.WriteLine("Import Setting Data for the ImportDirectory '{0}' was retrieved successfully.", importDirectory);
                }
                else
                {
                    Console.WriteLine("Failed to get the Import Setting Data");                    
                }
            }
            else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                importSettingData = (ManagementBaseObject)outParams["ImportSettingData"];
                Console.WriteLine("Import Setting Data for the ImportDirectory '{0}' was retrieved successfully.", importDirectory);
            }
            else
            {
                Console.WriteLine("Failed to get the Import Setting Data for the Import Directory :{0}", (UInt32)outParams["ReturnValue"]);
            }

            inParams.Dispose();
            outParams.Dispose();
            virtualSystemService.Dispose();

            importSettingData["GenerateNewId"] = true;
            importSettingData["CreateCopy"] = true;
            importSettingData["Name"] = "NewSampleVM";
            importSettingData["TargetResourcePaths"] = new string[] { (targetVhdResourcePath) };
            ManagementObject newSwitch = CreateSwitch(scope, "Switch_For_Import_Export_Sample", "Switch_For_Import_Export_Sample", 1024);
            importSettingData["TargetNetworkConnections"] = new string[] { (newSwitch.GetPropertyValue("Name").ToString())};
                        
            return importSettingData;
        }

        static void ImportVirtualSystemEx(string importDirectory)
        {
            string importCopyDirectory = importDirectory + "\\NewCopy";
            ManagementScope scope = new ManagementScope(@"root\virtualization", null);
            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementBaseObject importSettingData = GetVirtualSystemImportSettingData(scope, importDirectory, importCopyDirectory);

            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ImportVirtualSystemEx");
            inParams["ImportDirectory"] = importDirectory;
            inParams["ImportSettingData"] = importSettingData.GetText(TextFormat.CimDtd20);

            ManagementBaseObject outParams = virtualSystemService.InvokeMethod("ImportVirtualSystemEx", inParams, null);

            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    Console.WriteLine("VM were Imported successfully.");

                }
                else
                {
                    Console.WriteLine("Failed to Imported VM");
                }
            }
            else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                Console.WriteLine("VM were Imported successfully.");
            }
            else
            {
                Console.WriteLine("Import virtual system failed with error:{0}", outParams["ReturnValue"]);
            }

            inParams.Dispose();
            outParams.Dispose();
            virtualSystemService.Dispose();
        }

        static void Main(string[] args)
        {
            if (args != null && args.Length != 1)
            {
                Console.WriteLine("Usage: ImportVirtualSystemExMoreGranular importDirectory");                
                return;
            }
            ImportVirtualSystemEx(args[0]);
        }
    }
}

VB
option explicit 

dim objWMIService dim managementService dim switchService dim fileSystem

const JobStarting = 3 const JobRunning = 4 const JobCompleted = 7 const wmiStarted = 4096 const wmiSuccessful = 0

Main()

'----------------------------------------------------------------- ' Main '----------------------------------------------------------------- Sub Main() dim computer, objArgs, importDirectory, generateNewID

set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")
computer = "."
set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization")
set managementService = objWMIService.ExecQuery("select * from Msvm_VirtualSystemManagementService").ItemIndex(0)
set switchService = objWMIService.ExecQuery("select * from Msvm_VirtualSwitchManagementService").ItemIndex(0)


set objArgs = WScript.Arguments
if WScript.Arguments.Count = 1 then
    importDirectory = objArgs.Unnamed.Item(0)
else
    WScript.Echo "usage: cscript ImportVirtualSystemEx-MoreGranular.vbs importDirectoryName"
    WScript.Quit(1)
end if

if ImportVirtualSystemEx(importDirectory) then
    WriteLog "Done"
    WScript.Quit(0)
else
    WriteLog "ImportVirtualSystemEx Failed."
    WScript.Quit(1)
end if

End Sub

'----------------------------------------------------------------- ' Create a virtual switch by calling CreateSwitch WMI method '----------------------------------------------------------------- Function CreateSwitch(name, friendlyName, learnableAddress)

dim objInParam, objOutParams

set CreateSwitch = Nothing
set objInParam = switchService.Methods_("CreateSwitch").InParameters.SpawnInstance_()
objInParam.FriendlyName = friendlyName
objInParam.Name = name
objInParam.NumLearnableAddresses = learnableAddress
objInParam.ScopeofResidence = null

set objOutParams = switchService.ExecMethod_("CreateSwitch", objInParam)

if objOutParams.ReturnValue = wmiSuccessful then
    set CreateSwitch = objWMIService.Get(objOutParams.CreatedVirtualSwitch)
else
    WriteLog Format1("CreateSwitch failed with error code {0}", objOutParams.ReturnValue)
end if

End Function

'----------------------------------------------------------------- ' GetVirtualSystemImportSettingData from a directory '----------------------------------------------------------------- Function GetVirtualSystemImportSettingData(importDirectory)

dim objInParam, objOutParams    

set objInParam = managementService.Methods_("GetVirtualSystemImportSettingData").InParameters.SpawnInstance_()
objInParam.ImportDirectory = importDirectory

set objOutParams = managementService.ExecMethod_("GetVirtualSystemImportSettingData", objInParam)

if objOutParams.ReturnValue = wmiStarted then
    if (WMIJobCompleted(objOutParams)) then
        set GetVirtualSystemImportSettingData = objOutParams.ImportSettingData
    end if
elseif objOutParams.ReturnValue = wmiSuccessful then
    set GetVirtualSystemImportSettingData = objOutParams.ImportSettingData
else
    WriteLog Format1("GetVirtualSystemImportSettingData failed with ReturnValue {0}", objOutParams.ReturnValue)
end if

End Function '----------------------------------------------------------------- ' ImportVirtualSystem from a directory '----------------------------------------------------------------- Function ImportVirtualSystemEx(importDirectory)

dim objInParam, objOutParams
dim newDataRoot
dim importSettingData
dim newTargetResourcePaths, newTargetNetworkConnections, newSwitch    

newTargetResourcePaths = Array(1)
'Folders in newTargetResourcePaths should be existing
newTargetResourcePaths(0) = importDirectory & "\Temp.vhd"

newTargetNetworkConnections = Array(1)
newTargetNetworkConnections(0) = "Switch_For_Import_Export_Sample"

set newSwitch = CreateSwitch(newTargetNetworkConnections(0), newTargetNetworkConnections(0), 1024)

ImportVirtualSystemEx = false
set objInParam = managementService.Methods_("ImportVirtualSystemEx").InParameters.SpawnInstance_()
objInParam.ImportDirectory = importDirectory

set importSettingData = GetVirtualSystemImportSettingData(importDirectory)
importSettingData.GenerateNewId = true
importSettingData.CreateCopy = true
importSettingData.Name = "NewSampleVM-WithFixups"
importSettingData.TargetResourcePaths = newTargetResourcePaths
importSettingData.TargetNetworkConnections = newTargetNetworkConnections
importSettingData.Put_

objInParam.ImportSettingData = importSettingData.GetText_(1)

set objOutParams = managementService.ExecMethod_("ImportVirtualSystemEx", objInParam)

if objOutParams.ReturnValue = wmiStarted then
    if (WMIJobCompleted(objOutParams)) then
        ImportVirtualSystemEx = true
    end if
elseif objOutParams.ReturnValue = wmiSuccessful then
    ImportVirtualSystemEx = true
else
    WriteLog Format1("ImportVirtualSystemEx failed with ReturnValue {0}", objOutParams.ReturnValue)
end if

End Function

'----------------------------------------------------------------- ' Handle wmi Job object '----------------------------------------------------------------- Function WMIJobCompleted(outParam)

dim WMIJob, jobState

set WMIJob = objWMIService.Get(outParam.Job)

WMIJobCompleted = true

jobState = WMIJob.JobState

while jobState = JobRunning or jobState = JobStarting
    WriteLog Format1("In progress... {0}% completed.",WMIJob.PercentComplete)
    WScript.Sleep(1000)
    set WMIJob = objWMIService.Get(outParam.Job)
    jobState = WMIJob.JobState
wend

if (jobState <> JobCompleted) then
    WriteLog Format1("ErrorCode:{0}", WMIJob.ErrorCode)
    WriteLog Format1("ErrorDescription:{0}", WMIJob.ErrorDescription)
    WMIJobCompleted = false
end if

End Function

'----------------------------------------------------------------- ' Create the console log files. '----------------------------------------------------------------- Sub WriteLog(line) dim fileStream set fileStream = fileSystem.OpenTextFile(".\ImportVirtualSystemEx-MoreGranular.log", 8, true) WScript.Echo line fileStream.WriteLine line fileStream.Close

End Sub

'------------------------------------------------------------------------------ ' The string formatting functions to avoid string concatenation. '------------------------------------------------------------------------------ Function Format1(myString, arg0) Format1 = Replace(myString, "{0}", arg0) End Function