WIN1@Codename

Codename

Hyper-V をプログラムでどうにかしてみる VBScript その5 (仮想マシンの削除)

作った仮想マシンを削除するには

Option Explicit

Dim strServerName, strVMName, strNetworkName, strDiskPath, objWMIService, objManagementService
strServerName = "."
strVMName = "TestVM"  
strNetworkName = "LAN - 仮想ネットワーク"
strDiskPath = "E:\Hyper-V\TestVM\TestVM.vhd"
Set objWMIService = GetObject("winmgmts:\\" & strServerName & "\root\virtualization")
Set objManagementService = objWMIService.ExecQuery("SELECT * FROM Msvm_VirtualSystemManagementService").ItemIndex(0)

Call DeleteVM(strVMName)

Function DeleteVM(strVMName)
    Dim objComputerSystem
    Set objComputerSystem = objWMIService.ExecQuery("SELECT * FROM Msvm_ComputerSystem WHERE ElementName = '" & strVMName & "'").ItemIndex(0)

    Dim objVirtualSystemManagementService
    Set objVirtualSystemManagementService = objWMIService.ExecQuery("SELECT * FROM Msvm_VirtualSystemManagementService").ItemIndex(0)

    Dim objInParam, objOutParams
    Set objInParam = objManagementService.Methods_("DestroyVirtualSystem").InParameters.SpawnInstance_()
    objInParam.ComputerSystem = objComputerSystem.Path_.Path
    Set objOutParams = objManagementService.ExecMethod_("DestroyVirtualSystem", objInParam)

    Call JobCompleted(objOutParams, objWMIService)
End Function

Function JobCompleted(objOutParams, objWMIService)
    Dim objJob
    If (objOutParams.ReturnValue = 0) Then
        Wscript.Echo "OK"
    ElseIf (objOutParams.ReturnValue <> 4096) Then
        Wscript.Echo "NG"
    Else  
        Set objJob = objWMIService.Get(objOutParams.Job)
        While (objJob.JobState = 3) Or (objJob.JobState = 4)
WScript.Sleep(1000)
Set objJob = objWMIService.Get(objOutParams.Job)
        Wend
        If (objJob.JobState <> 7) Then
Wscript.Echo "NG"
Wscript.Echo "ErrorCode:" & objJob.ErrorCode
Wscript.Echo "ErrorDescription:" & objJob.ErrorDescription
        Else
Wscript.Echo "OK"
        End If
    End If
End Function

と、なりますね。

コメント

コメントの投稿


管理者にだけ表示を許可する

トラックバック

トラックバック URL
http://codename2010.blog11.fc2.com/tb.php/161-6370cb8b
この記事にトラックバックする(FC2ブログユーザー)

FC2Ad