xHyper-VBackup.cmdlets.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# ProcessWMIJob is a generic function that waits for WMI job's to
# complete and returns appropriate success/failure cases.
# This function was originally written and documented on
# Taylor Brown's blog at:
# http://blogs.msdn.com/b/taylorb/archive/2008/06/18/hyper-v-wmi-rich-error-messages-for-non-zero-returnvalue-no-more-32773-32768-32700.aspx
filter ProcessWMIJob
{
    param
    (
        [WMI]$WmiClass = $null,
        [string]$MethodName = $null
    )
    $errorCode = 0
    $returnObject = $_

    if ($_.ReturnValue -eq 4096)
    {
        $Job = [WMI]$_.Job
        $returnObject = $Job

        while ($Job.JobState -eq 4)
        {
            Write-Progress -Activity $Job.Caption -Status ($Job.JobStatus + " - " + $Job.PercentComplete + "%") -PercentComplete $Job.PercentComplete
            Start-Sleep -seconds 1
            $Job.PSBase.Get()
        }
        if ($Job.JobState -ne 7)
        {
            if ($Job.ErrorDescription -ne "")
            {
                Write-Error $Job.ErrorDescription
                Throw $Job.ErrorDescription
            }
            else
            {
                $errorCode = $Job.ErrorCode
            }
        }
        Write-Progress -Activity $Job.Caption -Status $Job.JobStatus -PercentComplete 100 -Completed:$true

    }
    elseif($_.ReturnValue -ne 0)
    {
        $errorCode = $_.ReturnValue
    }

    if ($errorCode -ne 0)
    {
        Write-Error "Hyper-V WMI Job Failed!"
        if ($WmiClass -and $MethodName)
        {
            $psWmiClass = [WmiClass]("\\" + $WmiClass.__SERVER + "\" + $WmiClass.__NAMESPACE + ":" + $WmiClass.__CLASS)
            $psWmiClass.PSBase.Options.UseAmendedQualifiers = $TRUE
            $MethodQualifierValues = ($psWmiClass.PSBase.Methods[$MethodName].Qualifiers)["Values"]
            $indexOfError = [System.Array]::IndexOf(($psWmiClass.PSBase.Methods[$MethodName].Qualifiers)["ValueMap"].Value, [string]$errorCode)
            if (($indexOfError -ne "-1") -and $MethodQualifierValues)
            {
                Throw "ReturnCode: ", $errorCode, " ErrorMessage: '", $MethodQualifierValues.Value[$indexOfError], "' - when calling $MethodName"
            }
            else
            {
                Throw "ReturnCode: ", $errorCode, " ErrorMessage: 'MessageNotFound' - when calling $MethodName"
            }
        }
        else
        {
            Throw "ReturnCode: ", $errorCode, "When calling $MethodName - for rich error messages provide classpath and method name."
        }
    }
    return $returnObject
}


function Convert-VmBackupCheckpoint
{
    Param(
      [Parameter(Mandatory=$True)]
      [System.Management.ManagementObject]$BackupCheckpoint = $null
    )

    # Retrieve an instance of the snapshot management service
    $Msvm_VirtualSystemSnapshotService = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_VirtualSystemSnapshotService

    # Convert the snapshot to a reference point, this function returns a job object.
    $job = $Msvm_VirtualSystemSnapshotService.ConvertToReferencePoint($BackupCheckpoint)

    # Wait for the job to complete.
    ($job | ProcessWMIJob -WmiClass $Msvm_VirtualSystemSnapshotService -MethodName "ConvertToReferencePoint") | Out-Null

    # The new reference point object is related to the job, GetReleated
    # always returns an array in this case there is only one member
    $refPoint = (([WMI]$job.Job).GetRelated("Msvm_VirtualSystemReferencePoint") | % {$_})

    # Return the reference point object
    return $refPoint
}

function Export-VMBackupCheckpoint
{
    [CmdletBinding(DefaultParametersetname="vmname")]
    Param(
      [Parameter(Mandatory=$True, ParameterSetName="vmname")]
      [string]$VmName = [String]::Empty,
      [Parameter(Mandatory=$True, ParameterSetName="vmid")]
      [string]$VmId = [String]::Empty,

      [Parameter(Mandatory=$True)]
      [string]$DestinationPath = [String]::Empty,

      [Parameter(Mandatory=$True)]
      [System.Management.ManagementObject]$BackupCheckpoint = $null,

      [System.Management.ManagementObject]$ReferencePoint = $null,

      [bool]$noWait = $false
    )

    # Retrieve an instance of the virtual machine management service
    $Msvm_VirtualSystemManagementService = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_VirtualSystemManagementService

    if ($PsCmdlet.ParameterSetName -eq "vmname"){
        $filter = "ElementName='$vmName'"
    } else {
        $filter = "Name='$VmId'"
    }
    # Retrieve an instance of the virtual machine computer system that will be snapshoted
    $Msvm_ComputerSystem = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter $filter

    # Retrieve an instance of the Export Setting Data Class (this is used to inform the export operation)
    # GetReleated always returns an array in this case there is only one member
    $Msvm_VirtualSystemExportSettingData = ($Msvm_ComputerSystem.GetRelated("Msvm_VirtualSystemExportSettingData","Msvm_SystemExportSettingData",$null,$null, $null, $null, $false, $null) | % {$_})

    # Specify the export options
        # CopySnapshotConfiguration
        # 0: ExportAllSnapshots - All snapshots will be exported with the VM.
        # 1: ExportNoSnapshots - No snapshots will be exported with the VM.
        # 2: ExportOneSnapshot - The snapshot identified by the SnapshotVirtualSystem property will be exported with the VM.
        # 3: ExportOneSnapshotUseVmId - The snapshot identified by the SnapshotVirtualSystem property will be exported with the VM. Using the VMs ID.
        $Msvm_VirtualSystemExportSettingData.CopySnapshotConfiguration = 3

        # CopyVmRuntimeInformation
        # Indicates whether the VM runtime information will be copied when the VM is exported. (i.e. saved state)
        $Msvm_VirtualSystemExportSettingData.CopyVmRuntimeInformation = $false

        # CopyVmStorage
        # Indicates whether the VM storage will be copied when the VM is exported. (i.e. VHDs/VHDx files)
        $Msvm_VirtualSystemExportSettingData.CopyVmStorage = $true

        # CreateVmExportSubdirectory
        # Indicates whether a subdirectory with the name of the VM will be created when the VM is exported.
        $Msvm_VirtualSystemExportSettingData.CreateVmExportSubdirectory = $false

        # SnapshotVirtualSystem
        # Path to a Msvm_VirtualSystemSettingData instance that represents the snapshot to be exported with the VM.
        $Msvm_VirtualSystemExportSettingData.SnapshotVirtualSystem = $BackupCheckpoint

        # DifferentialBase
        # Base for differential export. This is either path to a Msvm_VirtualSystemReferencePoint instance that
        # represents the reference point or path to a Msvm_VirtualSystemSettingData instance that
        # represents the snapshot to be used as a base for differential export. If the CopySnapshotConfiguration
        # property is not set to 3(ExportOneSnapshotUseVmId), this property is ignored."
        $Msvm_VirtualSystemExportSettingData.DifferentialBase = $ReferencePoint

        # StorageConfiguration
        # Indicates what should be the VHD path in the exported configuration.
        # 0: StorageConfigurationCurrent - The exported configuration would point to the current VHD.
        # 1: StorageConfigurationBaseVhd - The exported configuration would point to the base VHD.
        $Msvm_VirtualSystemExportSettingData.StorageConfiguration = 1

    #Export the virtual machine snapshot, this method returns a job object.
    $job = $Msvm_VirtualSystemManagementService.ExportSystemDefinition($Msvm_ComputerSystem, $DestinationPath, $Msvm_VirtualSystemExportSettingData.GetText(1))

    if (!$noWait)
    {
        ($job | ProcessWMIJob -WmiClass $Msvm_VirtualSystemManagementService -MethodName "ExportSystemDefinition") | Out-Null
    }
}

function Get-VmBackupCheckpoints
{
    [CmdletBinding(DefaultParametersetname="vmname")]
    Param(
      [Parameter(Mandatory=$True, ParameterSetName="vmid")]
      [string]$VmId = [String]::Empty,
      [Parameter(Mandatory=$True, ParameterSetName="vmname")]
      [string]$VmName = [String]::Empty
    )

    if ($PsCmdlet.ParameterSetName -eq "vmname"){
        $filter = "ElementName='$vmName'"
    } else {
        $filter = "Name='$VmId'"
    }

    # Retrieve an instance of the virtual machine computer system that contains recovery checkpoints
    $Msvm_ComputerSystem = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter $filter

    # Retrieve all snapshot associations for the virtual machine
    $allSnapshotAssociations = $Msvm_ComputerSystem.GetRelationships("Msvm_SnapshotOfVirtualSystem")

    # Enumerate across all of the instances and add all recovery snapshots to an array
    $virtualSystemSnapshots = @()
    $enum = $allSnapshotAssociations.GetEnumerator()
    $enum.Reset()
    while($enum.MoveNext())
    {
        if (([WMI] $enum.Current.Dependent).VirtualSystemType -eq "Microsoft:Hyper-V:Snapshot:Recovery")
        {
            $virtualSystemSnapshots += ([WMI] $enum.Current.Dependent)
        }
    }

    # Return the array of recovery snapshots
    $virtualSystemSnapshots
}

function Get-VmReferencePoints
{
    [CmdletBinding(DefaultParametersetname="vmname")]
    Param(
      [Parameter(Mandatory=$True, ParameterSetName="vmid")]
      [string]$VmId = [String]::Empty,
      [Parameter(Mandatory=$True, ParameterSetName="vmname")]
      [string]$VmName = [String]::Empty
    )

    if ($PsCmdlet.ParameterSetName -eq "vmname"){
        $filter = "ElementName='$vmName'"
    } else {
        $filter = "Name='$VmId'"
    }
    # Retrieve an instance of the virtual machine computer system that contains reference points
    $Msvm_ComputerSystem = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter $filter

    # Retrieve all refrence associations of the virtual machine
    $allrefPoints = $Msvm_ComputerSystem.GetRelationships("Msvm_ReferencePointOfVirtualSystem")

    # Enumerate across all of the instances and add all recovery points to an array
    $virtualSystemRefPoint = @()
    $enum = $allrefPoints.GetEnumerator()
    $enum.Reset()
    while($enum.MoveNext())
    {
        $virtualSystemRefPoint += ([WMI] $enum.Current.Dependent)
    }

    # Return the array of recovery points
    $virtualSystemRefPoint
}

function New-VmBackupCheckpoint
{
    [CmdletBinding(DefaultParametersetname="vmname")]
    Param(
      [Parameter(Mandatory=$True, ParameterSetName="vmid")]
      [string]$VmId = [String]::Empty,
      [Parameter(Mandatory=$True, ParameterSetName="vmname")]
      [string]$VmName = [String]::Empty,

      [ValidateSet('ApplicationConsistent','CrashConsistent')]
      [string]$ConsistencyLevel = "ApplicationConsistent"
    )

    # Retrieve an instance of the virtual machine management service
    $Msvm_VirtualSystemManagementService = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_VirtualSystemManagementService

    # Retrieve an instance of the virtual machine snapshot service
    $Msvm_VirtualSystemSnapshotService = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_VirtualSystemSnapshotService

    if ($PsCmdlet.ParameterSetName -eq "vmname"){
        $filter = "ElementName='$vmName'"
    } else {
        $filter = "Name='$VmId'"
    }
    # Retrieve an instance of the virtual machine computer system that will be snapshotted
    $Msvm_ComputerSystem = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem -Filter $filter

    # Create an instance of the Msvm_VirtualSystemSnapshotSettingData, this class provides options on how the checkpoint will be created.
    $Msvm_VirtualSystemSnapshotSettingData = ([WMIClass]"\\.\root\virtualization\v2:Msvm_VirtualSystemSnapshotSettingData").CreateInstance()

    # Identify the consistency level for the snapshot.
    # 1: Application Consistent
    # 2: Crash Consistent
    switch ($ConsistencyLevel)
    {
        "ApplicationConsistent" {
        $Msvm_VirtualSystemSnapshotSettingData.ConsistencyLevel = 1
        }

        "CrashConsistent" {
        $Msvm_VirtualSystemSnapshotSettingData.ConsistencyLevel = 2
        }

        default {
        throw "Unexpected Consistancy Level Specified"
        }
    }

    # Specify the behavior for disks that cannot be snapshotted (i.e. pass-through, virtual fibre channel)
    $Msvm_VirtualSystemSnapshotSettingData.IgnoreNonSnapshottableDisks = $true

    # Create the virtual machine snapshot, this method returns a job object.
    $job = $Msvm_VirtualSystemSnapshotService.CreateSnapshot(
        $Msvm_ComputerSystem,
        $Msvm_VirtualSystemSnapshotSettingData.GetText(2),
        32768)

    # Waits for the job to complete and processes any errors.
    ($job | ProcessWMIJob -WmiClass $Msvm_VirtualSystemSnapshotService -MethodName "CreateSnapshot") | Out-Null

    # Retrieves the snapshot object resulting from the snapshot.
    $snapshot = (([WMI]$job.Job).GetRelated("Msvm_VirtualSystemSettingData") | % {$_})

    # Returns the snapshot instance
    return $snapshot
}

function Remove-VmReferencePoint
{
    Param(
      [Parameter(Mandatory=$True)]
      [System.Management.ManagementObject]$ReferencePoint = $null
    )


    # Retrieve an instance of the virtual machine refrence point service
    $Msvm_VirtualSystemReferencePointService = Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_VirtualSystemReferencePointService

    # Removes the virtual machine reference, this method returns a job object.
    $job = $Msvm_VirtualSystemReferencePointService.DestroyReferencePoint($ReferencePoint)

    # Waits for the job to complete and processes any errors.
    ($job | ProcessWMIJob -WmiClass $Msvm_VirtualSystemReferencePointService -MethodName "DestroyReferencePoint") | Out-Null
}