Click to Rate and Give Feedback
MSDN
MSDN Library
Hyper-V
 DefineVirtualSystem Method of the M...

  Switch on low bandwidth view
DefineVirtualSystem Method of the Msvm_VirtualSystemManagementService Class

Creates a new virtual computer system instance. Properties that are not specified will be populated with default values.

Syntax

MOF

uint32 DefineVirtualSystem(
  [in]   string SystemSettingData,
  [in]   string ResourceSettingData[],
  [in]   CIM_VirtualSystemSettingData REF SourceSetting,
  [out]  CIM_ComputerSystem REF DefinedSystem,
  [out]  CIM_ConcreteJob REF Job
);

Parameters

SystemSettingData [in]

An embedded instance of the CIM_VirtualSystemSettingData or Msvm_VirtualSystemGlobalSettingData class. This parameter is required.

ResourceSettingData [in]

An optional parameter that contains a number of embedded instances of the CIM_ResourceAllocationSettingData class (or derived classes thereof). Together these instances describe the virtual resources of the virtual computer system. A default set of devices will be created for the virtual system regardless of whether this parameter is set. For example, processor and memory are automatically created and configured with default values.

SourceSetting [in]

A reference to an existing instance of CIM_VirtualSystemSettingData to use as a template for the new virtual computer system. The settings described in this object, as well as those in the associated CIM_ResourceAllocationSettingData instances (via the Msvm_VirtualSystemSettingDataComponent association), will be reflected in the new virtual computer system.

DefinedSystem [out]

A reference to the newly created 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

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 creates a virtual system. The referenced utilities can be found in Common Utilities for the Virtualization Samples.

using System;
using System.Management;

namespace HyperVSamples
{
    class DefineVirtualSystemClass
    {
        static string GetVirtualSystemGlobalSettingDataInstance(ManagementScope scope)
        {
            ManagementPath settingPath = new ManagementPath("Msvm_VirtualSystemGlobalsettingData");

            ManagementClass globalSettingClass = new ManagementClass(scope, settingPath, null);
            ManagementObject globalSettingData = globalSettingClass.CreateInstance();
            globalSettingData["ElementName"] = "My First VM";

            string settingData = globalSettingData.GetText(TextFormat.CimDtd20);

            globalSettingData.Dispose();
            globalSettingClass.Dispose();

            return settingData;
        }

        static ManagementObject DefineVirtualSystem(string vmName)
        {
            ManagementObject definedSystem = null;
            ManagementScope scope = new ManagementScope(@"root\virtualization", null);
            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("DefineVirtualSystem");
            inParams["ResourcesettingData"] = null;
            inParams["Sourcesetting"] = null;
            inParams["SystemsettingData"] = GetVirtualSystemGlobalSettingDataInstance(scope);

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

            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    definedSystem = new ManagementObject(outParams["DefinedSystem"].ToString());
                    Console.WriteLine("{0} was created successfully.", definedSystem["ElementName"]);
                }
                else
                {
                    Console.WriteLine("Failed to define virtual system");
                }
            }
            else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                definedSystem = new ManagementObject(outParams["DefinedSystem"].ToString());
                Console.WriteLine("{0} was created successfully.", definedSystem["ElementName"]);
            }
            else
            {
                Console.WriteLine("Define virtual system failed with error {0}", outParams["ReturnValue"]);
            }

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

            return definedSystem;
        }

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

The following VBScript sample creates 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, vmName
    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
        vmName = objArgs.Unnamed.Item(0)
    else
        WScript.Echo "usage: cscript DefineVirtualSystem.vbs vmName"
        WScript.Quit(1)
    end if

    if DefineVirtualSystem(vmName) then
        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "DefineVirtualSystem failed."
        WScript.Quit(1)
    end if

End Sub

'-----------------------------------------------------------------
' Define a virtual system
'-----------------------------------------------------------------
Function DefineVirtualSystem(vmName)

    dim globalsettingData, objInParam, objOutParams, wmiStatus
    
    DefineVirtualSystem = false
    set globalsettingData = objWMIService.Get("Msvm_VirtualSystemGlobalsettingData").SpawnInstance_()
    globalsettingData.ElementName = vmName
    set objInParam = managementService.Methods_("DefineVirtualSystem").InParameters.SpawnInstance_()
    objInParam.ResourcesettingData = null
    objInParam.Sourcesetting = null
    objInParam.SystemsettingData = globalsettingData.GetText_(1)
    
    set objOutParams = managementService.ExecMethod_("DefineVirtualSystem", objInParam)
    
    wmiStatus = objOutParams.ReturnValue

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

End Function

'-----------------------------------------------------------------
' Handle wmi Job object
'-----------------------------------------------------------------
Function WMIJobCompleted(outParam)
    WriteLog "Function WMIJobCompleted"
    
    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(".\ADDSCSIContoller.log", 8, true)
    WScript.Echo line
    fileStream.WriteLine line
    fileStream.Close

End Sub


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

'------------------------------------------------------------------------------
' 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

Send comments about this topic to Microsoft

Build date: 4/30/2009

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker