ImportVirtualSystem Method of the Msvm_VirtualSystemManagementService Class Home
ImportVirtualSystem Method of the Msvm_VirtualSystemManagementService Class

Beginning with Windows Server 2008 R2 this method is deprecated. Use the ImportVirtualSystemEx method.

Windows Server 2008:  Imports a virtual computer system definition from file. The resulting virtual computer system will be in the "Defined" state.

Syntax

uint32 ImportVirtualSystem(
  [in]   string ImportDirectory,
  [in]   boolean GenerateNewID,
  [out]  CIM_ConcreteJob REF Job
);

Parameters

ImportDirectory [in]

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 methods.

GenerateNewID [in]

Indicates whether to reuse the unique identifier for the virtual computer system. If this parameter is TRUE, it is guaranteed that the identifier will not conflict with the identifier of an existing virtual computer system.

It can be useful to specify FALSE to track a specific virtual computer system across an export/import cycle, as the identifier for the virtual computer system will be the same as it was before the export. However, clients must ensure that the unique identifier is not already in use by an existing virtual computer system.

Job [out]

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

Return Value

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.

Remarks

The import directory will not be the same as the export directory specified in ExportVirtualSystem. The ExportVirtualSystem method creates a new subdirectory to store the virtual computer system data to enable exporting multiple virtual computer systems to the same export directory. This subdirectory must be passed as the ImportDirectory parameter to this method.

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.


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

namespace HyperVSamples
{
    class ImportVirtualSystemClass
    {
        static void ImportVirtualSystem(string importDirectory, string generateNewID)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization", null);
            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("ImportVirtualSystem");
            inParams["GenerateNewID"] = generateNewID;
            inParams["ImportDirectory"] = importDirectory;

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

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

                }
                else
                {
                    Console.WriteLine("Failed to import 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 != 2)
            {
                Console.WriteLine("Usage: ImportVirtualSystem importDirectory generateNewID");
                Console.WriteLine("generateNewID:true|false");
                return;
            }
            ImportVirtualSystem(args[0], args[1]);
        }
    }
}

The following VBScript sample imports a virtual system.


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 = 2 then
        importDirectory = objArgs.Unnamed.Item(0)
        generateNewID = objArgs.Unnamed.Item(1)
    else
        WScript.Echo "usage: cscript ImportVirtualSystem.vbs importDirectoryName generateNewID"
        WScript.Echo "generateNewID:true|false"
        WScript.Quit(1)
    end if
   
    if ImportVirtualSystem(importDirectory, generateNewID) then
        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "importDirectory Failed."
        WScript.Quit(1)
    end if
End Sub


'-----------------------------------------------------------------
' ImportVirtualSystem from a directory
'-----------------------------------------------------------------
Function ImportVirtualSystem(importDirectory, generateNewID)

    dim objInParam, objOutParams
    
    ImportVirtualSystem = false
    set objInParam = managementService.Methods_("ImportVirtualSystem").InParameters.SpawnInstance_()
    objInParam.GenerateNewID = generateNewID
    objInParam.ImportDirectory = importDirectory
    
    set objOutParams = managementService.ExecMethod_("ImportVirtualSystem", objInParam)

    if objOutParams.ReturnValue = wmiStarted then
        if (WMIJobCompleted(objOutParams)) then
            ImportVirtualSystem = true
        end if
    elseif objOutParams.ReturnValue = wmiSuccessful then
        ImportVirtualSystem = 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(".\ImportVirtualSystem.log", 8, true)
    WScript.Echo line
    fileStream.WriteLine line
    fileStream.Close

End Sub

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

Requirements

Minimum supported clientNone supported
Minimum supported serverWindows Server 2008
MOFWindowsVirtualization.mof
Namespace\\.\Root\Virtualization

See Also

Msvm_VirtualSystemManagementService
ImportVirtualSystemEx

Send comments about this topic to Microsoft

Build date: 10/8/2009

© 2009 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View