Click to Rate and Give Feedback
MSDN
MSDN Library
Hyper-V
 CreateVirtualSystemSnapshot Method ...
CreateVirtualSystemSnapshot Method of the Msvm_VirtualSystemManagementService Class

Creates a snapshot of a virtual computer system that is in the "Enabled", "Disabled", or "Suspended" state. The result of the snapshot is a new instance of Msvm_VirtualSystemSettingData representing the settings for the virtual computer system at the time that the snapshot is taken. In addition, a new instance of each CIM_ResourceAllocationSettingData object will also be created to represent the settings for the devices in the virtual system at the time that the snapshot is taken.

Syntax

uint32 CreateVirtualSystemSnapshot(
  [in]   CIM_ComputerSystem REF SourceSystem,
  [out]  CIM_VirtualSystemSettingData REF SnapshotSettingData,
  [out]  CIM_ConcreteJob REF Job
);

Parameters

SourceSystem [in]

A reference to the virtual computer system to be snapshotted.

SnapshotSettingData [out]

The CIM_VirtualSystemSettingData instance that was created to represent the snapshot.

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.

Examples - C#

The following C# sample creates a snapshot. The referenced utilities can be found in Common Utilities for the Virtualization Samples.

using System;
using System.Management;

namespace HyperVSamples
{
    class CreateVirtualSystemSnapshotClass
    {
        static void CreateVirtualSystemSnapshot(string vmName)
        {
            ManagementScope scope = new ManagementScope(@"root\virtualization", null);
            ManagementObject virtualSystemService = Utility.GetServiceObject(scope, "Msvm_VirtualSystemManagementService");

            ManagementObject vm = Utility.GetTargetComputer(vmName, scope);

            ManagementBaseObject inParams = virtualSystemService.GetMethodParameters("CreateVirtualSystemSnapshot");
            inParams["SourceSystem"] = vm.Path.Path;

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

            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    Console.WriteLine("Snapshot was created successfully.");

                }
                else
                {
                    Console.WriteLine("Failed to create snapshot VM");
                }
            }
            else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                Console.WriteLine("Snapshot was created successfully.");
            }
            else
            {
                Console.WriteLine("Create virtual system snapshot failed with error {0}", outParams["ReturnValue"]);
            }

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

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

Examples - VBScript

The following VBScript sample creates a snapshot.

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, vm
    
    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 CreateVirtualSystemSnapshot.vbs vmName"
        WScript.Quit(1)
    end if
    

    set vm = GetComputerSystem(vmName)

    if CreateVirtualSystemSnapshot(vm) then
        WriteLog "Done"
        WScript.Quit(0)
    else
        WriteLog "CreateVirtualSystemSnapshot Failed."
        WScript.Quit(1)
    end if
    
End Sub

'-----------------------------------------------------------------
' Retrieve Msvm_VirtualComputerSystem from base on its ElementName
'-----------------------------------------------------------------
Function GetComputerSystem(vmElementName)
    On Error Resume Next
    dim query
    query = Format1("select * from Msvm_ComputerSystem where ElementName = '{0}'", vmElementName)
    set GetComputerSystem = objWMIService.ExecQuery(query).ItemIndex(0)
    if (Err.Number <> 0) then
        WriteLog Format1("Err.Number: {0}", Err.Number)
        WriteLog Format1("Err.Description:{0}",Err.Description)
        WScript.Quit(1)
    end if
End Function

'-----------------------------------------------------------------
' Create a virtual system snapshot
'-----------------------------------------------------------------
Function CreateVirtualSystemSnapshot(vm)

    dim objInParam, objOutParams

    CreateVirtualSystemSnapshot = false
    set objInParam = managementService.Methods_("CreateVirtualSystemSnapshot").InParameters.SpawnInstance_()
    objInParam.SourceSystem = vm.Path_.Path
    
    set objOutParams = managementService.ExecMethod_("CreateVirtualSystemSnapshot", objInParam)

    if (objOutParams.ReturnValue = wmiStarted) then
        if (WMIJobCompleted(objOutParams)) then
            CreateVirtualSystemSnapshot = true
        end if
    elseif (objOutParams.ReturnValue = wmiSuccessful) then
        CreateVirtualSystemSnapshot = true
    else
        WriteLog Format1("CreateVirtualSystemSnapshot 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(".\CreateVirtualSystemSnapshot.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

MOFWindowsVirtualization.mof
Namespace\\.\Root\Virtualization

See Also

Msvm_VirtualSystemManagementService


Send comments about this topic to Microsoft

Build date: 10/23/2008

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