Export (0) Print
Expand All

ImportVirtualSystemEx method of the Msvm_VirtualSystemManagementService class

Hyper-V

Imports a virtual computer system definition from a file. The resulting virtual computer system will be in the "Disabled" state.

Syntax


uint32 ImportVirtualSystemEx(
  [in]   string ImportDirectory,
  [in]   string ImportSettingData,
  [out]  CIM_ConcreteJob REF Job
);

Parameters

ImportDirectory [in]

Type: string

The fully qualified path to the directory that represents a previously exported virtual computer system. This file must have been generated by a previous call to the ExportVirtualSystem or ExportVirtualSystemEx method.

ImportSettingData [in]

Type: string

An instance of the Msvm_VirtualSystemImportSettingData class returned from the GetVirtualSystemImportSettingData method that represents the virtual computer system to be imported.

Job [out]

Type: CIM_ConcreteJob

An optional reference that is returned if the operation is executed asynchronously. If present, the returned reference to an instance of the CIM_ConcreteJob class can be used to monitor progress and to obtain the result of the method.

Return value

Type: uint32

If this method is executed synchronously, it returns 0 if it succeeds. If this method is executed asynchronously, it returns 4096 and the Job output parameter can be used to track the progress of the asynchronous operation. Any other return value indicates an error. The return value can be one of the following values.

Completed with No Error (0)
Method Parameters Checked - Job Started (4096)
Failed (32768)
Access Denied (32769)
Not Supported (32770)
Status is unknown (32771)
Timeout (32772)
Invalid parameter (32773)
System is in used (32774)
Invalid state for this operation (32775)
Incorrect data type (32776)
System is not available (32777)
Out of memory (32778)

Remarks

Access to the Msvm_VirtualSystemManagementService class might be restricted by UAC Filtering. For more information, see User Account Control and WMI.

Examples

The following C# sample imports a virtual system. The referenced utilities can be found in Common Utilities for the Virtualization Samples.

Important  To function correctly, the following code must be run on the VM host server, and must be run with Administrator privileges.


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

namespace HyperVSamples
{
    class ImportVirtualSystemExClass
    {
        static ManagementBaseObject GetVirtualSystemImportSettingData(ManagementScope scope, string importDirectory, string rootDirectoryToCopy)
        {
            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["TargetVmDataRoot"] = rootDirectoryToCopy;
            importSettingData["TargetSnapshotDataRoot"] = rootDirectoryToCopy;
            importSettingData["TargetVhdDataRoot"] = rootDirectoryToCopy;
            
            return importSettingData;
        }

        static void ImportVirtualSystemEx(string importDirectory)
        {
            string importCopyDirectory =  importDirectory + "\\NewCopy"; //Path specified should exist            
            if (Directory.Exists(importCopyDirectory))
            {
                Directory.Delete(importCopyDirectory, true);
            }
            Directory.CreateDirectory(importCopyDirectory);
                        
            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: ImportVirtualSystemEx importDirectory");                
                return;
            }
            ImportVirtualSystemEx(args[0]);
        }
    }
}


The following VBScript sample imports a virtual system.

Important  To function correctly, the following code must be run on the VM host server, and must be run with Administrator privileges.


option explicit 

dim objWMIService
dim managementService
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 objArgs = WScript.Arguments
    if WScript.Arguments.Count = 1 then
        importDirectory = objArgs.Unnamed.Item(0)
    else
        WScript.Echo "usage: cscript ImportVirtualSystemEx.vbs importDirectoryName"
        WScript.Quit(1)
    end if
   
    if ImportVirtualSystemEx(importDirectory) then
        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "importDirectory Failed."
        WScript.Quit(1)
    end if
End Sub

'-----------------------------------------------------------------
' 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("ImportVirtualSystem failed with ReturnValue {0}", objOutParams.ReturnValue)
    end if

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

    dim objInParam, objOutParams
    dim newDataRoot
    dim importSettingData, copyDir, fileSysObj

    ImportVirtualSystemEx = false    
        
    newDataRoot = importDirectory & "\NewCopy" 
    
    'Path in newDataRoot folder should be existing
    set fileSysObj  = CreateObject("Scripting.FileSystemObject")
    if fileSysObj.FolderExists(newDataRoot) then
    fileSysObj.DeleteFolder(newDataRoot)        
    end if
    copyDir = fileSysObj.CreateFolder(newDataRoot) 
    
    set objInParam = managementService.Methods_("ImportVirtualSystemEx").InParameters.SpawnInstance_()
    objInParam.ImportDirectory = importDirectory

    set importSettingData = GetVirtualSystemImportSettingData(importDirectory)
    importSettingData.GenerateNewId = true
    importSettingData.CreateCopy = true
    importSettingData.Name = "NewSampleVM"
    importSettingData.TargetVmDataRoot = newDataRoot
    importSettingData.TargetSnapshotDataRoot = newDataRoot
    importSettingData.TargetVhdDataRoot = newDataRoot
    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("ImportVirtualSystem 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.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


For more examples demonstrating the ImportVirtualSystemEx method, see Importing Virtual Machines.

Requirements

Minimum supported client

None supported

Minimum supported server

Windows Server 2008 R2

End of client support

None supported

End of server support

Windows Server 2012

Namespace

\\.\Root\Virtualization

MOF

WindowsVirtualization.mof

See also

Msvm_VirtualSystemManagementService
ImportVirtualSystem

 

 

Community Additions

ADD
Show:
© 2014 Microsoft