Hyper-V-Backup.ps1

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
336
337
338

<#PSScriptInfo
 
.VERSION 3.5.1
 
.GUID c7fb05cc-1e20-4277-9986-523020060668
 
.AUTHOR Mike Galvin twitter.com/digressive
 
.COMPANYNAME
 
.COPYRIGHT (C) Mike Galvin. All rights reserved.
 
.TAGS Hyper-V Virtual Machines Backup Export Permissions
 
.LICENSEURI
 
.PROJECTURI https://gal.vin/2017/09/18/vm-backup-for-hyper-v
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES Windows 10/Windows Serevr2016/Windows 2012 R2 Hyper-V PowerShell Management Modules
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
#>


<#
    .SYNOPSIS
    Creates a full backup of running Hyper-V Virtual Machines.
    .DESCRIPTION
    Creates a full backup of running Hyper-V Virtual Machines.
 
    This script will:
     
    Create a full backup of Virtual Machine(s), complete with configuration, snapshot, and VHD files.
    If the -noprems switch is used, the script will shutdown the VM and copy all the files to the backup location, then start the VM.
    You should use the -noperms switch if Hyper-V does not have the appropriate permissions to the backup location to do an export.
    If the -noprems switch is NOT used, the script will use the built-in export function.
 
    Important note: This script should be run on a Hyper-V host. The Hyper-V PowerShell management modules should be installed.
     
    .PARAMETER BackupTo
    The path the Virtual Machines should be backed up to.
    A folder will be created named after the Hyper-V host and each VM will have it's own folder inside.
 
    .PARAMETER l
    The path to output the log file to.
    The file name will be HyperV-Backup-YYYY-MM-dd-HH-mm-ss.log
 
    .PARAMETER NoPerms
    Instructs the script to shutdown the running VM(s) to do the file-copy based backup, instead of the Hyper-V export function.
    When multipul VMs are running, the first VM (alphabetically) will be shutdown, backed up, and then started, then the next and so on.
 
    .EXAMPLE
    Hyper-V-Backup.ps1 -backupto \\nas\vms -noperms -l E:\scripts -sendto me@contoso.com -from hyperv@contoso.com -smtp smtp.outlook.com -user user -pwd p@ssw0rd -usessl
    This will shutdown all running VMs and back up their files to \\nas\vms. The log file will be output to E:\scripts and sent via email.
#>


[CmdletBinding()]
Param(
    [parameter(Mandatory=$true)]
    [alias("backupto")]
    $Backup,
    [alias("l")]
    $LogPath,
    [alias("sendto")]
    $MailTo,
    [alias("from")]
    $MailFrom,
    [alias("smtp")]
    $SmtpServer,
    [alias("user")]
    $SmtpUser,
    [alias("pwd")]
    $SmtpPwd,
    [switch]$UseSsl,
    [switch]$NoPerms)

## If logging is configured, start log
If ($LogPath)
{
    $LogFile = ("HyperV-Backup-{0:yyyy-MM-dd-HH-mm-ss}.log" -f (Get-Date))
    $Log = "$LogPath\$LogFile"

    ## If the log file already exists, clear it
    $LogT = Test-Path -Path $Log
    If ($LogT)
    {
        Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Value "****************************************"
    Add-Content -Path $Log -Value "$(Get-Date -format g) Log started"
    Add-Content -Path $Log -Value ""
}

## Set variables for computer name and get all running VMs
$Vs = $Env:ComputerName
$Vms = Get-VM | Where-Object {$_.State -eq 'Running'}

## Logging
If ($LogPath)
{
    Add-Content -Path $Log -Value "$(Get-Date -format g) This virtual host is: $Vs"
    Add-Content -Path $Log -Value "$(Get-Date -format g) The following VMs will be backed up:"

    ForEach ($vm in $Vms)
    {
        Add-Content -Path $Log -Value "$($vm.name)"
    }
}

## Test for backup folder existence
ForEach ($vm in $Vms)
{
    $VmExport = Test-Path "$Backup\$Vs\$($vm.name)"
    If ($VmExport -eq $true)
    {
        Remove-Item "$Backup\$Vs\$($vm.name)" -Recurse -Force
        
        If ($LogPath)
        {
            Add-Content -Path $Log -Value "$(Get-Date -format g) Removing previous backup of $($vm.name)"
        }
        Start-Sleep -s 5
    }
}

## If no perms switch is set do the following commands
If ($NoPerms) 
{
    ## For each VM do the following
    ForEach ($vm in $Vms)
    {
        ## Create directories
        New-Item "$Backup\$Vs\$($vm.name)\Virtual Machines" -ItemType Directory -Force
        New-Item "$Backup\$Vs\$($vm.name)\VHD" -ItemType Directory -Force
        New-Item "$Backup\$Vs\$($vm.name)\Snapshots" -ItemType Directory -Force

        ## For logging, test for creation of backup folders, report if non existant.
        If ($LogPath)
        {
            $VmFolderTest = Test-Path "$Backup\$Vs\$($vm.name)\Virtual Machines"
            If ($VmFolderTest -eq $true)
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully created backup folder $Backup\$Vs\$($vm.name)\Virtual Machines"
            }

            Else
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem creating folder $Backup\$Vs\$($vm.name)\Virtual Machines"
            }

            $VmVHDTest = Test-Path "$Backup\$Vs\$($vm.name)\VHD"
            If ($VmVHDTest -eq $true)
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully created backup folder $Backup\$Vs\$($vm.name)\VHD"
            }

            Else
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem creating folder $Backup\$Vs\$($vm.name)\VHD"
            }
            
            $VmSnapTest = Test-Path "$Backup\$Vs\$($vm.name)\Snapshots"
            If ($VmSnapTest -eq $true)
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully created backup folder $Backup\$Vs\$($vm.name)\Snapshots"
            }

            Else
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem creating folder $Backup\$Vs\$($vm.name)\Snapshots"
            }
        }

        ## Stop the VM
        Stop-VM $vm

        ## For logging
        If ($LogPath)
        {
            Add-Content -Path $Log -Value "$(Get-Date -format g) Stopping VM: $($vm.name)"
        }

        Start-Sleep -s 5

        ## Copy the config files and folders
        Copy-Item "$($vm.ConfigurationLocation)\Virtual Machines\$($vm.id)" "$Backup\$Vs\$($vm.name)\Virtual Machines\" -Recurse -Force
        Copy-Item "$($vm.ConfigurationLocation)\Virtual Machines\$($vm.id).*" "$Backup\$Vs\$($vm.name)\Virtual Machines\" -Recurse -Force

        ## For logging
        If ($LogPath)
        {
            $VmConfigTest = Test-Path "$Backup\$Vs\$($vm.name)\Virtual Machines\*"
            If ($VmConfigTest -eq $true)
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully copied $($vm.name) configuration to $Backup\$Vs\$($vm.name)\Virtual Machines"
            }

            Else
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem copying the configuration for $($vm.name)"
            }
        }

        ## Copy the VHD
        Copy-Item $vm.HardDrives.Path -Destination "$Backup\$Vs\$($vm.name)\VHD\" -Recurse -Force

        ## For logging
        If ($LogPath)
        {
            $VmVHDCopyTest = Test-Path "$Backup\$Vs\$($vm.name)\VHD\*"
            If ($VmVHDCopyTest -eq $true)
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully copied $($vm.name) VHDs to $Backup\$Vs\$($vm.name)\VHD"
            }

            Else
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem copying the VHDs for $($vm.name)"
            }
        }

        ## Get the snapshots
        $Snaps = Get-VMSnapshot $vm

        ## For each snapshot do the following
        ForEach ($snap in $Snaps)
        {

            ## Copy the snapshot config files and folders
            Copy-Item "$($vm.ConfigurationLocation)\Snapshots\$($snap.id)" "$Backup\$Vs\$($vm.name)\Snapshots\" -Recurse -Force
            Copy-Item "$($vm.ConfigurationLocation)\Snapshots\$($snap.id).*" "$Backup\$Vs\$($vm.name)\Snapshots\" -Recurse -Force

            ## For logging
            If ($LogPath)
            {
                $VmSnapCopyTest = Test-Path "$Backup\$Vs\$($vm.name)\Snapshots\*"
                If ($VmSnapCopyTest -eq $true)
                {
                    Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully copied checkpoint configuration for $($vm.name) to $Backup\$Vs\$($vm.name)\Snapshots"
                }

                Else
                {
                    Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem copying the checkpoint configuration for $($vm.name)"
                }
            }

            ## Copy the snapshot root VHD
            Copy-Item $snap.HardDrives.Path -Destination "$Backup\$Vs\$($vm.name)\VHD\" -Recurse -Force

            If ($LogPath)
            {
                Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully copied checkpoint VHDs for $($vm.name) to $Backup\$Vs\$($vm.name)\VHD"
            }
        }

        ## Start the VM and wait for 60 seconds before proceeding
        Start-VM $vm

        ## For logging
        If ($LogPath)
        {
            Add-Content -Path $Log -Value "$(Get-Date -format g) Starting VM: $($vm.name)"
        }

        Start-Sleep -s 60
    }
}

## If no perms is not set export the VM like normal
Else
{
    $Vms | Export-VM -Path "$Backup\$vs"

    ## For logging
    If ($LogPath)
    {
        $VmExportTest = Test-Path "$Backup\$Vs\*"
        If ($VmExportTest -eq $true)
        {
            Add-Content -Path $Log -Value "$(Get-Date -format g) Successfully exported specified VMs to $Backup\$Vs"
        }

        Else
        {
            Add-Content -Path $Log -Value "$(Get-Date -format g) ERROR: There was a problem exporting the specified VMs to $Backup\$Vs"
        }
    }
}

## If log was configured stop the log
If ($LogPath)
{
    Add-Content -Path $Log -Value ""
    Add-Content -Path $Log -Value "$(Get-Date -format g) Log finished"
    Add-Content -Path $Log -Value "****************************************"

    ## If email was configured, set the variables for the email subject and body
    If ($SmtpServer)
    {
        $MailSubject = "Hyper-V Backup Log"
        $MailBody = Get-Content -Path $Log | Out-String

        ## If an email password was configured, create a variable with the username and password
        If ($SmtpPwd)
        {
            $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $SmtpUser, $($SmtpPwd | ConvertTo-SecureString -AsPlainText -Force)

            ## If ssl was configured, send the email with ssl
            If ($UseSsl)
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -UseSsl -Credential $SmtpCreds
            }

            ## If ssl wasn't configured, send the email without ssl
            Else
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Credential $SmtpCreds
            }
        }

        ## If an email username and password were not configured, send the email without authentication
        Else
        {
            Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer
        }
    }
}

## End