Hyper-V上での仮想マシンのエクスポートとインポート

直接仮想マシンフォルダからエクスポート、インポートする手順

GMOインターネット株式会社 システム本部 樋口 勝一が担当するGMO最新ネット業界レポート-ソリューション編。

今回は、Hyper-V上での仮想マシンのエクスポートとインポートについてご紹介します。

Hyper-Vのエクスポートとインポート機能

Windows Server 2012 のHyper-Vからは、仮想マシンが稼働中であってもエクスポートが可能となり、仮想マシンをエスポーとすることなく、直接仮想マシンフォルダからインポートもできるようになりました。

とても便利になったHyper-Vのエクスポートとインポート機能ですが、インポートする場合では、新しい root\virtualization\v2 名前空間では少々手順が複雑化しており、

新しいメソッド「ImportSystemDefinition」を実行するだけではVMのインポートは完了せず、設定ファイルだけが作成されるだけとなっています。

新しいHyper-Vで、エクスポートから一通りのインポート作業が完了するまでの手順をご紹介します。

仮想マシンののエクスポート

WMI経由で仮想マシンのエクスポートを行う場合は、Msvm_VirtualSystemExportSettingDataクラスを使用します。

実際にコード内でMsvm_VirtualSystemExportSettingDataクラスでプロパティーを指定して、ExportSystemDefinition メソッドで実行します。

Msvm_VirtualSystemExportSettingDataクラスのプロパティーは以下となります。

CopySnapshotConfigurationエクスポートする場合にスナップショットを含めるか否か。(Windows Server 2012R2 からは「スナップショット」は「チェックポイント」とう名前に変更されました。)
全てのスナップショットを含める(ExportAllSnapshots)= 0
スナップショットを含まない(ExportNoSnapshots)= 1
スナップショットの一つをエクスポート(ExportOneSnapshot)= 2
※仮想マシンのスナップショットの1つだけを指定してエクスポートもできます。
CopyVmRuntimeInformation仮想マシンが保存された状態である場合にメモリ内容をエクスポートするか否か。メモリ内容が無い状態でインポートを実行すると、保存状態は破棄され停止状態で仮想マシンはインポートされます。
CopyVmStorageエクスポートに仮想ハードディスクを含めるか否か。
CreateVmExportSubdirectoryサブディレクトリを作成するか否か。
SnapshotVirtualSystemCopySnapshotConfiguration で ExportOneSnapshot(=2)を選択した場合に、エクスポートするスナップショットの Msvm_VirtualSystemSettingData クラスを指定する。

これらを踏まえた仮想マシンのエクスポートのサンプルコードは以下となります。

Imports System.Management
 
Module GMOReport
    Sub Main()
        Dim strUser As String = ""
        Dim strPass As String = ""
        Dim objManagementScope As ManagementScope = ConnectManagementScope("WinSvr2012R2", strUser, strPass)
        objManagementScope.Connect()

        Dim strVMName As String = "VM01"

        Call ExportVm(objManagementScope, strVMName, 0, True, True, True, "D:\Hyper-V\Exp", "")
    End Sub

    Function ConnectManagementScope(ByVal strServer As String, ByVal strAccount As String, ByVal strPassword As String) As ManagementScope
        Dim objConnectionOptions As New ConnectionOptions()
        objConnectionOptions.Impersonation = ImpersonationLevel.Impersonate 'WMI への接続に使用される偽装レベルを設定
        objConnectionOptions.EnablePrivileges = True 'WNI経由の操作のためにユーザー特権を有効にする
        objConnectionOptions.Username = strAccount
        objConnectionOptions.Password = strPassword
        Dim objManagementScope As New ManagementScope("\\" + strServer + "\root\virtualization\v2", objConnectionOptions)
        objManagementScope.Connect()
        Return (objManagementScope)
    End Function

    Function ExportVm(ByVal objManagementScope As ManagementScope, strVMName As String, intCopySnapshotConfiguration As Integer, blnCopyVmRuntimeInformation As Boolean, blnCopyVhd As Boolean, blnCreateSubdirectory As Boolean, ByVal strExportDirectory As String, strSnapshotName As String) As Boolean
        Dim objComputerSystem As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName = '" & strVMName & "'")).Get
            objComputerSystem = objManagementObject
        Next
   
        Dim objVirtualSystemsettingData As ManagementObject = Nothing
        If strSnapshotName <> "" Then
            For Each objManagementObject As ManagementObject In objComputerSystem.GetRelated("Msvm_VirtualSystemSettingData")
                If objManagementObject("ElementName") = strSnapshotName Then
                    objVirtualSystemsettingData = objManagementObject
                    Exit For
                End If
            Next
        End If
 
        Dim objVirtualSystemExportSettingData As New ManagementClass(objManagementScope, New ManagementPath("Msvm_VirtualSystemExportSettingData"), Nothing)
        Dim objVirtualSystemExportSettingDataInstance As ManagementObject = objVirtualSystemExportSettingData.CreateInstance
        objVirtualSystemExportSettingDataInstance("CopySnapshotConfiguration") = intCopySnapshotConfiguration 'ExportAllSnapshots:0 ExportNoSnapshots:1 ExportOneSnapshot:2
        objVirtualSystemExportSettingDataInstance("CopyVmRuntimeInformation") = blnCopyVmRuntimeInformation
        objVirtualSystemExportSettingDataInstance("CopyVmStorage") = blnCopyVhd
        objVirtualSystemExportSettingDataInstance("CreateVmExportSubdirectory") = blnCreateSubdirectory
        objVirtualSystemExportSettingDataInstance("SnapshotVirtualSystem") = objVirtualSystemsettingData
        Dim strExportSettingData As String = objVirtualSystemExportSettingDataInstance.GetText(TextFormat.CimDtd20)
  
        For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
            Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("ExportSystemDefinition")
            objParams("ComputerSystem") = objComputerSystem.Path.Path
            objParams("ExportDirectory") = strExportDirectory
            objParams("ExportSettingData") = strExportSettingData
            Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("ExportSystemDefinition", objParams, Nothing)
            Return JobComplete(objManagementBaseObject, objManagementScope)
        Next
    End Function

    Function JobComplete(ByVal objManagementBaseObject As ManagementBaseObject, ByVal objManagementScope As ManagementScope) As Boolean
        'JobState New = 2  Starting = 3  Running = 4  Suspended = 5  ShuttingDown = 6  Completed = 7  Terminated = 8  Killed = 9  Exception = 10  Service = 11
        If objManagementBaseObject("ReturnValue") <> 0 Then
            Dim strJobPath As String = objManagementBaseObject("Job")
            Dim objJob As New ManagementObject(objManagementScope, New ManagementPath(strJobPath), Nothing)
            objJob.Get()
            Do While objJob("JobState") = 3 Or objJob("JobState") = 4
                System.Threading.Thread.Sleep(1000)
                objJob.Get()
            Loop
            If objJob("JobState") <> 7 Then
                Console.WriteLine("ErrorCode=" & objJob("ErrorCode") & " JobState=" & objJob("JobState"))
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If
    End Function
End Module

エクスポートが成功すると、このようにスナップショットも含めてファオルダが作成されます。

仮想マシンのインポート

次にインポートです。先にも述べましたが、root\virtualization\v2 名前空間ではインポートがいくつかのステップによって実行されます。大まかな流れとしてはこのようになります。Hyper-V マネージャーの仮想マシンのインポートウィザードとほぼ同じ手順となります。

1. 仮想マシンをインポートするための設定ファイルを読み込み、実行するインポートの種類を指定する

ImportSystemDefinition

2. 仮想マシンの保存場所の設定

ModifySystemSettings

3. ハードディスクの保存場所の設定

ModifyResourceSettings

4. インポート設定の検証

ValidatePlannedSystem

5. インポートの実行
RealizePlannedSystem
6. インポート構成ファイルの削除
DestroySystem

1.仮想マシンをインポートするための設定ファイルを読み込む

仮想マシンをインポートするためには、Definition Fileと呼ばれるxmlの構成ファイルを読み込む必要があります。通常は、仮想マシンフォルダやエクスポートした仮想マシンフォルダの中の、「Virtual Machines」フォルダに 1D5E37BD-202C-4B76-B8C1-F4CFD3B67313.XML といったようなファイル名で保存されています。

Msvm_VirtualSystemManagementService クラスのImportSystemDefinition メソッドで各パラメーターを指定して実行します。

SystemDefinitionFile構成ファイルのフルパスを指定します。
SnapshotFolderエクスポートした仮想マシンにスナップショットがある場合に、スナップショットの構成ファイル(xml)があるフォルダを指定します。
GenerateNewSystemIdentifier「実行するインポートの種類」のうち、「仮想マシンをインプレースで登録する(既存の一意なIDを使用する)」「仮想マシンを復元する(既存の一意なIDを使用する)」を選択した場合は「False」を、「仮想マシンをコピーする(新しい一意なIDを作成する)」の場合は「True」を指定します。

仮想マシンの設定ファイルの読み込みが成功すると、”C:\ProgramData\Microsoft\Windows\Hyper-V\Planned Virtual Machines” フォルダに、インポート候補の構成ファイルが作成されます。

以降の操作対象となるのは、仮想マシンではなく、インポート候補となっている仮想マシンが対象となります。

そのため、これまでは
SELECT * FROM Msvm_ComputerSystem
としていた操作対象となる仮想マシンの指定部分が

SELECT * FROM Msvm_PlannedComputerSystem
と変更になっている点に注意が必要です。

2.仮想マシンの保存場所の設定

インポートする時に仮想マシンのフォルダ構成を変更することができます。エクスポートファイルをバックアップとしてのリストアを行う場合は問題ありませんが、エクスポートファイルから仮想マシンのクローンを作る場合などはこの設定が必要となります。

エクスポートした仮想マシンの構成ファイルには、元々の仮想マシンの構成フォルダなどのパスが記載されており、エクスポート元の仮想マシンと同一の構成内容となっています。そのため、そのままインポートしてしまうと、パスなどが競合してしまうこととなるので、変更が必要となります。

変更対象となるのは、先ほど構成ファイルを読み込み、”C:\ProgramData\Microsoft\Windows\Hyper-V\Planned Virtual Machines” フォルダに保存された、インポート候補の構成ファイルとなります。

こちらの構成ファイルをMsvm_VirtualSystemSettingDataクラスのプロパティーを指定して、ModifySystemSettings メソッドで変更します。

Msvm_VirtualSystemSettingData クラスのプロパティーは以下となります。

ConfigurationDataRoot仮想マシンの構成フォルダ
SnapshotDataRootチェックポイント ストア
SwapFileDataRootスマート ページング フォルダ

今回は仮想マシンの構成フォルダを、すべてのフォルダパスとしています。

3.ハードディスクの保存場所の設定

仮想マシンの保存場所の設定変更同様に、仮想ハードディスクのパスも変更する必要があります。また、指定するパスに仮想ハードディスクファイル(vhdx)や、スナップショットファイル(avhdx)が事前に配置されている必要があります。エクスポートフォルダ内から、該当フォルダにファイルをコピーもしくは、移動をしておきます。

Msvm_StorageAllocationSettingDataクラスのプロパティーを指定して、ModifyResourceSettings メソッドで変更します。変更するMsvm_StorageAllocationSettingDat クラスのプロパティーは以下となります。

HostResourcet仮想ハードディスクのファイルパスを指定します。

今回は仮想マシンの構成フォルダをルートパスとしています。

スナップショットのファイル(avhdx)パスについては、「1.ImportSystemDefinition」でスナップショットの構成フォルダを指定することで、自動的にパスを書き換えてくるので、設定変更の必要はありません。

4.インポート設定の検証

“C:\ProgramData\Microsoft\Windows\Hyper-V\Planned Virtual Machines” フォルダに保存された、インポート候補の構成ファイルをインポートを実行する前に事前に問題がないか検証を行います。

XMLのファイル構文や、仮想ハードディスクのパスが有効なものであるか否かなどが検証対象となります。Msvm_VirtualSystemManagementService クラスの ValidatePlannedSystem メソッドで検証を実行します。

5.インポートの実行

インポート設定の検証に問題がなければ、最実際の仮想マシンとしてHyper-V上にインポートを実行します。

“Msvm_VirtualSystemManagementService クラスの RealizePlannedSystem メソッドで実行します。

6.インポート構成ファイルの削除

読み込んだインポート構成ファイルを削除して完了となります。Msvm_VirtualSystemManagementService クラスの DestroySystem メソッドで実行します。

エクスポートファイルからクローンを作成する場合は、仮想マシンの名前も変更する必要があるので、仮想マシンの名前の変更方法も追記しておきます。

こちらは、インポートした仮想マシンのIDを元に名前変更を行っています。

実行結果は、このように仮想マシンのクローンとしてインポートが完了しました。

以上を踏まえて、仮想マシンのインポートの一通りの手順のサンプルコードを紹介します。

Imports System.Management
   
Module GMOReport    Sub Main()        Dim strUser As String = ""        Dim strPass As String = ""        Dim objManagementScope As ManagementScope = ConnectManagementScope("WinSvr2012R2", strUser, strPass)        objManagementScope.Connect() 
        Dim strVMName As String = "VM01"
 
        Call ImportVm(objManagementScope, True, "VM01", "D:\Hyper-V\Exp\VM01\Virtual Machines\1D5E37BD-202C-4B76-B8C1-F4CFD3B67313.XML", "D:\Hyper-V\Exp\VM01\Snapshots", "D:\Hyper-V\VM02", "D:\Hyper-V\VM02", "VM02")
    End Sub
 
    Function ConnectManagementScope(ByVal strServer As String, ByVal strAccount As String, ByVal strPassword As String) As ManagementScope
        Dim objConnectionOptions As New ConnectionOptions()
        objConnectionOptions.Impersonation = ImpersonationLevel.Impersonate 'WMI への接続に使用される偽装レベルを設定
        objConnectionOptions.EnablePrivileges = True 'WNI経由の操作のためにユーザー特権を有効にする
        objConnectionOptions.Username = strAccount
        objConnectionOptions.Password = strPassword
        Dim objManagementScope As New ManagementScope("\\" + strServer + "\root\virtualization\v2", objConnectionOptions)
        objManagementScope.Connect()
        Return (objManagementScope)
    End Function
 
 
    Function ImportVm(ByVal objManagementScope As ManagementScope, ByVal blnNewId As Boolean, strVMName As String, ByVal strImportConfigFilePath As String, strImportSnapshotFolder As String, strVMRootPath As String, strDiskRootPath As String, strNewVMName As String) As Boolean
        Dim strRealizedVmId As String = ""
        If ImportVmConfig(objManagementScope, strImportConfigFilePath, strImportSnapshotFolder, blnNewId) Then
            If ChangePlannedConfig(objManagementScope, strVMName, strVMRootPath) Then
                If ChangePlannedHardDisk(objManagementScope, strVMName, strDiskRootPath) Then
                    If ValidatePlannedVm(objManagementScope, strVMName) Then
                        If RealizePlannedVm(objManagementScope, strVMName, strRealizedVmId) Then
                            If RenameVM(objManagementScope, strRealizedVmId, strVMName, strNewVMName) Then
                                Return True
                            End If
                        End If
                    End If
                End If
            End If
        End If
        Call DeletePlannedVm(objManagementScope, strVMName)
        Return False
    End Function
 
    Function ImportVmConfig(ByVal objManagementScope As ManagementScope, ByVal strSystemDefinitionFilePath As String, strSnapshotFolder As String, ByVal blnNewId As Boolean) As Boolean
        For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
            Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("ImportSystemDefinition")
            objParams("SystemDefinitionFile") = strSystemDefinitionFilePath
            objParams("SnapshotFolder") = strSnapshotFolder
            objParams("GenerateNewSystemIdentifier") = blnNewId
            Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("ImportSystemDefinition", objParams, Nothing)
            Return JobComplete(objManagementBaseObject, objManagementScope)
        Next
    End Function
 
    Function ValidatePlannedVm(ByVal objManagementScope As ManagementScope, ByVal strVMName As String) As Boolean
        Dim objComputerSystem As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_PlannedComputerSystem WHERE ElementName = '" & strVMName & "'")).Get
            objComputerSystem = objManagementObject
        Next
        For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
            Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("ValidatePlannedSystem")
            objParams("PlannedSystem") = objComputerSystem.Path.Path
            Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("ValidatePlannedSystem", objParams, Nothing)
            Return JobComplete(objManagementBaseObject, objManagementScope)
        Next
    End Function
 
    Function RealizePlannedVm(ByVal objManagementScope As ManagementScope, ByVal strVMName As String, ByRef strRealizedVmId As String) As Boolean
        Dim objComputerSystem As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_PlannedComputerSystem WHERE ElementName = '" & strVMName & "'")).Get
            objComputerSystem = objManagementObject
        Next
        For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
            Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("RealizePlannedSystem")
            objParams("PlannedSystem") = objComputerSystem.Path.Path
            Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("RealizePlannedSystem", objParams, Nothing)
            Call JobComplete(objManagementBaseObject, objManagementScope)
 
            Dim objJob As New ManagementObject(objManagementBaseObject("Job").ToString())
            objJob.Scope = objManagementScope
            objJob.Get()
            For Each objManagementObject As ManagementObject In objJob.GetRelated("Msvm_ComputerSystem")
                strRealizedVmId = objManagementObject("Name")
            Next
            Return True
        Next
    End Function
 
    Function DeletePlannedVm(ByVal objManagementScope As ManagementScope, ByVal strVMName As String) As Boolean
        Dim objComputerSystem As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_PlannedComputerSystem WHERE ElementName = '" & strVMName & "'")).Get
            objComputerSystem = objManagementObject
        Next
        For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
           Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("DestroySystem")
           objParams("AffectedSystem") = objComputerSystem.Path.Path
           Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("DestroySystem", objParams, Nothing)
            Return JobComplete(objManagementBaseObject, objManagementScope)
        Next
    End Function
 
    Function ChangePlannedConfig(ByVal objManagementScope As ManagementScope, ByVal strVMName As String, ByVal strRootPath As String) As Boolean
        Dim objComputerSystem As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_PlannedComputerSystem WHERE ElementName = '" & strVMName & "'")).Get
            objComputerSystem = objManagementObject
        Next
 
        Dim objVirtualSystemsettingData As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In objComputerSystem.GetRelated("Msvm_VirtualSystemSettingData")
            If String.Compare(objManagementObject("ElementName").ToString, strVMName, True) = 0 Then
                objVirtualSystemsettingData = objManagementObject
                objVirtualSystemsettingData("ConfigurationDataRoot") = strRootPath
                objVirtualSystemsettingData("SnapshotDataRoot") = strRootPath
                objVirtualSystemsettingData("SwapFileDataRoot") = strRootPath
            End If
        Next
 
        For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
            Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("ModifySystemSettings")
            objParams("SystemSettings") = objVirtualSystemsettingData.GetText(TextFormat.CimDtd20)
            Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("ModifySystemSettings", objParams, Nothing)
            Return JobComplete(objManagementBaseObject, objManagementScope)
        Next
    End Function
 
    Function ChangePlannedHardDisk(ByVal objManagementScope As ManagementScope, ByVal strVMName As String, ByVal strDiskRootPath As String) As Boolean
        Dim objComputerSystem As ManagementObject = Nothing
        For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_PlannedComputerSystem WHERE ElementName = '" & strVMName & "'")).Get
            objComputerSystem = objManagementObject
        Next
 
         Dim objHardDisk As ManagementObject = Nothing
         Dim objVirtualSystemsettingData As ManagementObject = Nothing
         For Each objManagementObject As ManagementObject In objComputerSystem.GetRelated("Msvm_VirtualSystemSettingData")
             objVirtualSystemsettingData = objManagementObject
             For Each objResourceAllocationSettingData As ManagementObject In objVirtualSystemsettingData.GetRelated("Msvm_StorageAllocationSettingData")
                 If objResourceAllocationSettingData("ResourceType") = 31 Then 'Logical Disk  http://msdn.microsoft.com/en-us/library/hh859775(v=vs.85).aspx
                     objHardDisk = objResourceAllocationSettingData
                     Dim strOldPath As String = objHardDisk("HostResource")(0)
                     Dim strFileName As String = System.IO.Path.GetFileName(strOldPath)
                     Dim strNewDiskPath As String = System.IO.Path.Combine(strDiskRootPath, strFileName)
                     objHardDisk("HostResource") = New String(0) {strNewDiskPath} 'http://msdn.microsoft.com/en-us/library/cc136877(v=vs.85).aspx
                     For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
                         Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("ModifyResourceSettings")
                         Dim strResourceSettingData As String() = New String(0) {}
                         strResourceSettingData(0) = objHardDisk.GetText(TextFormat.CimDtd20)
                         objParams("ResourceSettings") = strResourceSettingData 'http://msdn.microsoft.com/en-us/library/hh850099(v=vs.85).aspx
                         Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("ModifyResourceSettings", objParams, Nothing)
                         Call JobComplete(objManagementBaseObject, objManagementScope)
                     Next
                 End If
             Next
         Next
         Return True
     End Function
  
     Function RenameVM(ByVal objManagementScope As ManagementScope, ByVal strVMID As String, ByVal strVMName As String, ByVal strNewVMName As String) As Boolean
         Dim objComputerSystem As ManagementObject = Nothing
         For Each objManagementObject As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_ComputerSystem WHERE Name = '" & strVMID & "'")).Get
             objComputerSystem = objManagementObject
         Next
  
         Dim objVirtualSystemsettingData As ManagementObject = Nothing
         For Each objManagementObject As ManagementObject In objComputerSystem.GetRelated("Msvm_VirtualSystemSettingData")
             If String.Compare(objManagementObject("ElementName").ToString, strVMName, True) = 0 Then
                 objVirtualSystemsettingData = objManagementObject
                 objVirtualSystemsettingData("ElementName") = strNewVMName
             End If
         Next
  
         For Each objVirtualSystemManagementService As ManagementObject In New ManagementObjectSearcher(objManagementScope, New ObjectQuery("SELECT * FROM Msvm_VirtualSystemManagementService")).Get
             Dim objParams As ManagementBaseObject = objVirtualSystemManagementService.GetMethodParameters("ModifySystemSettings")
             objParams("SystemSettings") = objVirtualSystemsettingData.GetText(TextFormat.CimDtd20)
             Dim objManagementBaseObject As ManagementBaseObject = objVirtualSystemManagementService.InvokeMethod("ModifySystemSettings", objParams, Nothing)
             Return JobComplete(objManagementBaseObject, objManagementScope)
         Next
     End Function
  
     Function JobComplete(ByVal objManagementBaseObject As ManagementBaseObject, ByVal objManagementScope As ManagementScope) As Boolean
         'JobState New = 2  Starting = 3  Running = 4  Suspended = 5  ShuttingDown = 6  Completed = 7  Terminated = 8  Killed = 9  Exception = 10  Service = 11
         If objManagementBaseObject("ReturnValue") <> 0 Then
             Dim strJobPath As String = objManagementBaseObject("Job")
             Dim objJob As New ManagementObject(objManagementScope, New ManagementPath(strJobPath), Nothing)
             objJob.Get()
             Do While objJob("JobState") = 3 Or objJob("JobState") = 4
                 System.Threading.Thread.Sleep(1000)
                 objJob.Get()
             Loop
             If objJob("JobState") <> 7 Then
                 Console.WriteLine("ErrorCode=" & objJob("ErrorCode") & " JobState=" & objJob("JobState"))
                 Return False
             Else
                 Return True
             End If
         Else
             Return True
         End If
     End Function
 End Module

今回のポイントとしては、インポート時に仮想ハードディスクのパスをきちんと指定することと、該当パスに仮想ハードディスクをきちんと配置しておくということになります。また、最新のHyper-Vではエクスポートは仮想マシンの稼働中でも可能となっている点も非常に便利な機能となっています。

いくつか複雑な手順がありましたが、Hyper-VマネージャーなどのGUIでは設定しきれないポイントまで細かく指定できるのがやはりWMIの利点となります。

是非ご利用ください。

サンプルコードをこちらからダウンロードいただけます。
 → SampleCode.zip(20.9KB)

*本文中に記載されている会社名および商品名・サービス名は、各社の商標 または登録商標です。

著書の紹介欄

Hyper-Vで本格的なサーバー仮想環境を構築。仮想環境を設定・操作できる!

できるPRO Windows Server 2016 Hyper-V

◇Hyper-Vのさまざまな機能がわかる ◇インストールからの操作手順を解説 ◇チェックポイントやレプリカも活用できる Windows Server 2016 Hyper-Vは、仮想化ソフトウェア基盤を提供する機能であり、クラウドの実現に不可欠のものです。 本書では、仮想化の基礎知識から、Hyper-Vでの仮想マシンや仮想スイッチの設定・操作、プライベートクラウドの構築、Azureとの連携などを解説します。

初めてのWindows Azure Pack本が発売

Windows Azure Pack プライベートクラウド構築ガイド

本書は、Windows Azure PackとHyper-Vを利用し、企業内IaaS(仮想マシン提供サービス)を構成するための、IT管理者に向けた手引書です。試用したサーバーは、最小限度の物理サーバーと仮想マシンで構成しています。Windows Azure Packに必要なコンポーネントのダウンロード、実際にプライベートクラウド構築する過程を、手順を追って解説しています。これからプライベートクラウドの構築を検討するうえで、作業負担の軽減に役立つ一冊です。

ブログの著者欄

樋口 勝一

GMOインターネットグループ株式会社

1999年6月GMOインターネットグループ株式会社に入社。Windows Serverをプラットフォームとしたサービス開発から運用・保守まで幅広く担当。講演登壇や出版、ネット記事連載などでマイクロソフト社と強い信頼関係を構築。「マイクロソフトMVPアワード」を15度受賞し、インターネットソリューションのスペシャリストとして活躍。

採用情報

関連記事

KEYWORD

採用情報

SNS FOLLOW

GMOインターネットグループのSNSをフォローして最新情報をチェック