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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
<#PSScriptInfo
 
.VERSION 21.11.09
 
.GUID c7fb05cc-1e20-4277-9986-523020060668
 
.AUTHOR Mike Galvin Contact: mike@gal.vin / twitter.com/mikegalvin_ / discord.gg/5ZsnJ5k
 
.COMPANYNAME Mike Galvin
 
.COPYRIGHT (C) Mike Galvin. All rights reserved.
 
.TAGS Hyper-V Virtual Machines Full Backup Export Permissions Zip History 7-Zip
 
.LICENSEURI
 
.PROJECTURI https://gal.vin/posts/vm-backup-for-hyper-v
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
#>


<#
    .SYNOPSIS
    Hyper-V Backup Utility - Flexible backup of Hyper-V Virtual Machines.
 
    .DESCRIPTION
    This script will create a full backup of virtual machines, complete with configuration, snapshots/checkpoints, and VHD files.
    This script should be run on a Hyper-V host and the Hyper-V PowerShell management modules should be installed.
 
    To send a log file via e-mail using ssl and an SMTP password you must generate an encrypted password file.
    The password file is unique to both the user and machine.
    To create the password file run this command as the user and on the machine that will use the file:
 
    $creds = Get-Credential
    $creds.Password | ConvertFrom-SecureString | Set-Content C:\scripts\ps-script-pwd.txt
 
    .PARAMETER BackupTo
    The path the virtual machines should be backed up to.
    Each VM will have its own folder inside this location.
    Do not add a trailing backslash.
 
    .PARAMETER List
    Enter the path to a txt file with a list of Hyper-V VM names to backup.
    If this option is not configured, all running VMs will be backed up.
 
    .PARAMETER Wd
    The path to the working directory to use for the backup before copying it to the final backup directory.
    Use a directory on local fast media to improve performance.
 
    .PARAMETER NoPerms
    Configures the utility to shut down the running VM(s) to do the file-copy based backup instead of using the Hyper-V export function.
    If no list is specified and multiple VMs are running, the process will run through the VMs alphabetically.
 
    .PARAMETER Keep
    Instructs the utility to keep a specified number of days’ worth of backups.
    VM backups older than the number of days specified will be deleted.
    Every effort has been taken to only remove backup files or folders generated by this utility.
 
    .PARAMETER Compress
    This option will create a zip file of each Hyper-V VM backup.
    Available disk space should be considered when using this option.
 
    .PARAMETER Sz
    Configure the utility to use 7-Zip to compress the VM backups.
    7-Zip must be installed in the default location ($env:ProgramFiles) if it is not found, Windows compression will be used as a fallback.
     
    .PARAMETER SzOptions
    Use this option to configure options for 7-Zip. The switches must be comma separated and surrounded by single quotes.
    For example, archive type, split files, password protection would be '-t7z,-v2G,-ppassword'
 
    .PARAMETER ShortDate
    Configure the script to use only the Year, Month and Day in backup filenames.
 
    .PARAMETER NoBanner
    Use this option to hide the ASCII art title in the console.
 
    .PARAMETER L
    The path to output the log file to.
    The file name will be Hyper-V-Backup_YYYY-MM-dd_HH-mm-ss.log.
    Do not add a trailing \ backslash.
 
    .PARAMETER Subject
    The subject line for the e-mail log. Encapsulate with single or double quotes.
    If no subject is specified, the default of "Hyper-V Backup Utility Log" will be used.
 
    .PARAMETER SendTo
    The e-mail address the log should be sent to.
 
    .PARAMETER From
    The e-mail address the log should be sent from.
 
    .PARAMETER Smtp
    The DNS name or IP address of the SMTP server.
 
    .PARAMETER Port
    The Port that should be used for the SMTP server.
 
    .PARAMETER User
    The user account to authenticate to the SMTP server.
 
    .PARAMETER Pwd
    The txt file containing the encrypted password for SMTP authentication.
 
    .PARAMETER UseSsl
    Configures the utility to connect to the SMTP server using SSL.
 
    .EXAMPLE
    Hyper-V-Backup.ps1 -BackupTo \\nas\vms -List C:\scripts\vms.txt -Wd E:\temp -NoPerms -Keep 30 -Compress -Sz
    -SzOptions '-t7z,-v2g,-ppassword' -L C:\scripts\logs -Subject 'Server: Hyper-V Backup' -SendTo me@contoso.com
    -From hyperv@contoso.com -Smtp smtp.outlook.com -User user -Pwd C:\scripts\ps-script-pwd.txt -UseSsl
 
    This will shutdown, one at a time, all the VMs listed in the file located in C:\scripts\vms.txt and back up
    their files to \\nas\vms, using E:\temp as a working directory. A .7z file for each VM folder will be created using
    7-zip. 7-zip will use 8 threads, medium compression and split the files in 2GB volumes. Any backups older than 30 days
    will also be deleted. The log file will be output to C:\scripts\logs and sent via e-mail with a custom subject line.
#>


## Set up command line switches.
[CmdletBinding()]
Param(
    [parameter(Mandatory=$True)]
    [alias("BackupTo")]
    $Backup,
    [alias("Keep")]
    $History,
    [alias("List")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $VmList,
    [alias("Wd")]
    $WorkDir,
    [alias("SzOptions")]
    $SzSwitches,
    [alias("L")]
    $LogPath,
    [alias("Subject")]
    $MailSubject,
    [alias("SendTo")]
    $MailTo,
    [alias("From")]
    $MailFrom,
    [alias("Smtp")]
    $SmtpServer,
    [alias("Port")]
    $SmtpPort,
    [alias("User")]
    $SmtpUser,
    [alias("Pwd")]
    [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
    $SmtpPwd,
    [switch]$UseSsl,
    [switch]$NoPerms,
    [switch]$Compress,
    [switch]$Sz,
    [switch]$ShortDate,
    [switch]$NoBanner)

If ($NoBanner -eq $False)
{
    Write-Host ""
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " _ _ __ __ ____ _ _ _ _ _ _ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | | | | \ \ / / | _ \ | | | | | | | (_) (_) | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | |__| |_ _ _ __ ___ _ _\ \ / / | |_) | __ _ ___| | ___ _ _ __ | | | | |_ _| |_| |_ _ _ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | __ | | | | '_ \ / _ \ '__\ \/ / | _ < / _ |/ __| |/ / | | | '_ \ | | | | __| | | | __| | | | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " | | | | |_| | |_) | __/ | \ / | |_) | (_| | (__| <| |_| | |_) | | |__| | |_| | | | |_| |_| | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " |_| |_|\__, | .__/ \___|_| \/ |____/ \__,_|\___|_|\_\\__,_| .__/ \____/ \__|_|_|_|\__|\__, | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " __/ | | | | __/ | "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " |___/|_| Mike Galvin https://gal.vin |_| Version 21.11.09 |___/ "
    Write-Host -ForegroundColor Yellow -BackgroundColor Black " "
    Write-Host ""
}

## If logging is configured, start logging.
## If the log file already exists, clear it.
If ($LogPath)
{
    ## Make sure the log directory exists.
    $LogPathFolderT = Test-Path $LogPath

    If ($LogPathFolderT -eq $False)
    {
        New-Item $LogPath -ItemType Directory -Force | Out-Null
    }

    $LogFile = ("Hyper-V-Backup_{0:yyyy-MM-dd_HH-mm-ss}.log" -f (Get-Date))
    $Log = "$LogPath\$LogFile"

    $LogT = Test-Path -Path $Log

    If ($LogT)
    {
        Clear-Content -Path $Log
    }

    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log started"
}

## Function to get date in specific format.
Function Get-DateFormat
{
    Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}

Function Get-DateShort
{
    Get-Date -Format "yyyy-MM-dd"
}

Function Get-DateLong
{
    Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
}

## Function for logging.
Function Write-Log($Type, $Evt)
{
    If ($Type -eq "Info")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [INFO] $Evt"
        }

        Write-Host "$(Get-DateFormat) [INFO] $Evt"
    }

    If ($Type -eq "Succ")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [SUCCESS] $Evt"
        }

        Write-Host -ForegroundColor Green "$(Get-DateFormat) [SUCCESS] $Evt"
    }

    If ($Type -eq "Err")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$(Get-DateFormat) [ERROR] $Evt"
        }

        Write-Host -ForegroundColor Red -BackgroundColor Black "$(Get-DateFormat) [ERROR] $Evt"
    }

    If ($Type -eq "Conf")
    {
        If ($Null -ne $LogPath)
        {
            Add-Content -Path $Log -Encoding ASCII -Value "$Evt"
        }

        Write-Host -ForegroundColor Cyan -Object "$Evt"
    }
}


##
## Start of backup Options function
##

Function OptionsRun
{
    ## Remove previous backup folders. -Keep switch and -Compress switch are NOT configured.
    If ($Null -eq $History -And $Compress -eq $False)
    {
        Write-Log -Type Info -Evt "(VM:$Vm) Removing previous backups"

        ## Remove all previous backup folders
        If ($ShortDate)
        {
            ## report old files to remove
            Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory
            Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

            ## remove old files
            Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Remove-Item -Recurse -Force
        }

        else {
            ## report old files to remove
            Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory
            Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

            ## remove old files
            Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Remove-Item -Recurse -Force
        }

        ## If working directory is configured by user, remove all previous backup folders
        If ($WorkDir -ne $Backup)
        {
            ## Make sure the backup directory exists.
            $BackupFolderT = Test-Path $Backup

            If ($BackupFolderT)
            {
                If ($ShortDate)
                {
                    ## report old files to remove
                    Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*" -Directory
                    Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*" -Directory | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                    ## remove old files
                    Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*" -Directory | Remove-Item -Recurse -Force
                }

                else {
                    ## report old files to remove
                    Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*_*-*-*" -Directory
                    Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                    ## remove old files
                    Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Remove-Item -Recurse -Force
                }
            }
        }
    }

    ## Remove previous backup folders older than X configured days. -Keep switch is configuired and -Compress switch is NOT.
    else {
        If ($Compress -eq $False)
        {
            Write-Log -Type Info -Evt "(VM:$Vm) Removing backup folders older than: $History days"

            ## Remove previous backup folders older than the configured number of days.
            If ($ShortDate)
            {
                ## report old files to remove
                Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                ## remove old files
                Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
            }

            else {
                ## report old files to remove
                Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                ## remove old files
                Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
            }

            ## If working directory is configured by user, remove all previous backup folders older than X configured days.
            If ($WorkDir -ne $Backup)
            {
                ## Make sure the backup directory exists.
                $BackupDirT = Test-Path $Backup

                If ($BackupDirT)
                {
                    If ($ShortDate)
                    {
                        ## report old files to remove
                        Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                        Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                        ## remove old files
                        Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
                    }

                    else {
                        ## report old files to remove
                        Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                        Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                        ## remove old files
                        Get-ChildItem -Path $Backup -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Recurse -Force
                    }
                }
            }
        }
    }

    ## Remove ALL previous backup files. -Keep switch is NOT configuired and -Compress switch IS.
    If ($Compress)
    {
        If ($Null -eq $History)
        {
            Write-Log -Type Info -Evt "(VM:$Vm) Removing all previous compressed backups"

            ## Remove all previous compressed backups
            If ($ShortDate)
            {
                Remove-Item "$WorkDir\$VmFixed-*-*-*.*" -Force
            }

            else {
                Remove-Item "$WorkDir\$VmFixed-*-*-*_*-*-*.*" -Force
            }

            ## If working directory is configured by user, remove all previous backup files.
            If ($WorkDir -ne $Backup)
            {
                ## Make sure the backup directory exists.
                $BackupFolderT = Test-Path $Backup

                If ($BackupFolderT)
                {
                    If ($ShortDate)
                    {
                        Remove-Item "$Backup\$VmFixed-*-*-*.*" -Force
                    }

                    else {
                        Remove-Item "$Backup\$VmFixed-*-*-*_*-*-*.*" -Force
                        }
                }
            }
        }

        ## Remove previous backup files older than X days. -Keep and -Compress switch are configured.
        else {

            Write-Log -Type Info -Evt "(VM:$Vm) Removing compressed backups older than: $History days"

            ## Remove previous compressed backups older than the configured number of days.
            If ($ShortDate)
            {
                ## report old files to remove
                Get-ChildItem -Path "$WorkDir\$VmFixed-*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                Get-ChildItem -Path "$WorkDir\$VmFixed-*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                ## remove old files
                Get-ChildItem -Path "$WorkDir\$VmFixed-*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Force
            }

            else {
                ## report old files to remove
                Get-ChildItem -Path "$WorkDir\$VmFixed-*-*-*_*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                Get-ChildItem -Path "$WorkDir\$VmFixed-*-*-*_*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                ## remove old files
                Get-ChildItem -Path "$WorkDir\$VmFixed-*-*-*_*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Force
            }

            ## If working directory is configured by user, remove previous backup files older than X days.
            If ($WorkDir -ne $Backup)
            {
                ## Make sure the backup directory exists.
                $BackupFolderT = Test-Path $Backup

                If ($BackupFolderT)
                {
                    If ($ShortDate)
                    {
                        ## report old files to remove
                        Get-ChildItem -Path "$Backup\$VmFixed-*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                        Get-ChildItem -Path "$Backup\$VmFixed-*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                        ## remove old files
                        Get-ChildItem -Path "$Backup\$VmFixed-*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Force
                    }

                    else {
                        ## report old files to remove
                        Get-ChildItem -Path "$Backup\$VmFixed-*-*-*_*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Where-Object CreationTime –lt (Get-Date).AddDays(-$History)
                        Get-ChildItem -Path "$Backup\$VmFixed-*-*-*_*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Select-Object -Property Name, CreationTime | Format-Table -HideTableHeaders | Out-File -Append $Log -Encoding ASCII

                        ## remove old files
                        Get-ChildItem -Path "$Backup\$VmFixed-*-*-*_*-*-*.*" | Where-Object CreationTime –lt (Get-Date).AddDays(-$History) | Remove-Item -Force
                    }
                }
            }
        }

        ## If -Compress and -Sz are configured AND 7-zip is installed - compress the backup folder, if it isn't fallback to Windows compression.
        If ($Sz -eq $True -AND $7zT -eq $True)
        {
            Write-Log -Type Info -Evt "(VM:$Vm) Compressing backup using 7-Zip compression"

            ## If -Shortdate is configured, test for an old backup file, if true append a number (and increase the number if file still exists) before the file extension.
            If ($ShortDate)
            {
                ## If using 7zip's split file feature with short dates, we need to handle the files a little differently.
                If ($SzSwSplit -like "-v*")
                {
                    $ShortDateT = Test-Path -Path ("$WorkDir\$VmFixed-$(Get-DateShort).*.*")

                    If ($ShortDateT)
                    {
                        Write-Log -Type Info -Evt "(VM:$Vm) File $VmFixed-$(Get-DateShort) already exists, appending number"
                        $i = 1
                        $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                        $ShortDateExistT = Test-Path -Path "$WorkDir\$ShortDateNN.*.*"

                        If ($ShortDateExistT)
                        {
                            do {
                                $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                                $ShortDateExistT = Test-Path -Path "$WorkDir\$ShortDateNN.*.*"
                            } until ($ShortDateExistT -eq $false)
                        }

                        ## 7-zip compression with shortdate configured and a number appened.
                        try {
                            & "$env:programfiles\7-Zip\7z.exe" $SzSwSplit -bso0 a ("$WorkDir\$ShortDateNN") "$WorkDir\$Vm\*"
                        }
                        catch{
                            $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                        }
                    }

                    else {
                        ## 7-zip compression with shortdate configured and no need for a number appened.
                        try {
                            & "$env:programfiles\7-Zip\7z.exe" $SzSwSplit -bso0 a ("$WorkDir\$VmFixed-$(Get-DateShort)") "$WorkDir\$Vm\*"
                        }
                        catch{
                            $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                        }
                    }
                }

                else
                {
                    $ShortDateT = Test-Path -Path ("$WorkDir\$VmFixed-$(Get-DateShort).*")

                    If ($ShortDateT)
                    {
                        Write-Log -Type Info -Evt "(VM:$Vm) File $VmFixed-$(Get-DateShort) already exists, appending number"
                        $i = 1
                        $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                        $ShortDateExistT = Test-Path -Path "$WorkDir\$ShortDateNN.*"

                        If ($ShortDateExistT)
                        {
                            do {
                                $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                                $ShortDateExistT = Test-Path -Path "$WorkDir\$ShortDateNN.*"
                            } until ($ShortDateExistT -eq $false)
                        }

                        ## 7-zip compression with shortdate configured and a number appened.
                        try {
                            & "$env:programfiles\7-Zip\7z.exe" $SzSwSplit -bso0 a ("$WorkDir\$ShortDateNN") "$WorkDir\$Vm\*"
                        }
                        catch{
                            $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                        }
                    }

                    ## 7-zip compression with shortdate configured and no need for a number appened.
                    try {
                        & "$env:programfiles\7-Zip\7z.exe" $SzSwSplit -bso0 a ("$WorkDir\$VmFixed-$(Get-DateShort)") "$WorkDir\$Vm\*"
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                    }
                }
            }

            else {
                ## 7-zip compression with longdate.
                try {
                    & "$env:programfiles\7-Zip\7z.exe" $SzSwSplit -bso0 a ("$WorkDir\$VmFixed-$(Get-DateLong)") "$WorkDir\$Vm\*"
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }
        }

        ## Compress the backup folder using Windows compression. -Compress is configured, -Sz switch is not, or it is and 7-zip isn't detected.
        ## This is also the "fallback" windows compression code.
        else {
            Write-Log -Type Info -Evt "(VM:$Vm) Compressing backup using Windows compression"
            Add-Type -AssemblyName "system.io.compression.filesystem"

            If ($ShortDate)
            {
                $ShortDateT = Test-Path -Path ("$WorkDir\$VmFixed-$(Get-DateShort).zip")

                If ($ShortDateT)
                {
                    Write-Log -Type Info -Evt "(VM:$Vm) File $VmFixed-$(Get-DateShort) already exists, appending number"
                    $i = 1
                    $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                    $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN

                    If ($ShortDateExistT)
                    {
                        do {
                            $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}.zip" -f $i++)
                            $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN
                        } until ($ShortDateExistT -eq $false)
                    }

                    ## Windows compression with shortdate configured and a number appened.
                    try {
                        [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$ShortDateNN"))
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                    }
                }

                else {
                    try {
                        [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$VmFixed-$(Get-DateShort).zip"))
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                    }
                }
            }

            else {
                try {
                    [io.compression.zipfile]::CreateFromDirectory("$WorkDir\$Vm", ("$WorkDir\$VmFixed-$(Get-DateLong).zip"))
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }
        }

        ## Remove the VMs export folder.
        Get-ChildItem -Path $WorkDir -Filter "$Vm" -Directory | Remove-Item -Recurse -Force

        ## If working directory has been configured by the user, move the compressed backup to the backup folder and rename to include the date.
        If ($WorkDir -ne $Backup)
        {
            ## Make sure the backup directory exists.
            $BackupFolderT = Test-Path $Backup

            If ($BackupFolderT -eq $False)
            {
                Write-Log -Type Info -Evt "Backup directory $Backup doesn't exist. Creating it."
                New-Item $Backup -ItemType Directory -Force | Out-Null
            }

            ## Get the exact name of the backup file and append numbers onto the filename, keeping the extention intact.
            If ($ShortDate)
            {
                If ($SzSwSplit -like "-v*")
                {
                    $SzSplitFiles = Get-ChildItem -Path ("$WorkDir\$VmFixed-$(Get-DateShort).*.*") -File
                    
                    ForEach ($SplitFile in $SzSplitFiles) {
                        $ShortDateT = Test-Path -Path "$Backup\$($SplitFile.name)"

                        If ($ShortDateT)
                        {
                            Write-Log -Type Info -Evt "(VM:$Vm) File $($SplitFile.name) already exists, appending number"
                            $FileExist = Get-ChildItem -Path "$Backup\$($SplitFile.name)" -File
                            $i = 1

                            $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++ + $FileExist.Extension)
                            $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN

                            If ($ShortDateExistT)
                            {
                                do {
                                    $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++ + $FileExist.Extension)
                                    $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                                } until ($ShortDateExistT -eq $false)
                            }

                            try {
                                Get-ChildItem -Path $SplitFile | Move-Item -Destination $Backup\$ShortDateNN -ErrorAction 'Stop'
                            }
                            catch{
                                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                            }
                        }

                        else {
                            try {
                                Get-ChildItem -Path $SplitFile | Move-Item -Destination $Backup\$ShortDateNN -ErrorAction 'Stop'
                            }
                            catch{
                                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                            }
                        }
                    }
                }

                else{
                    $BackupFile = Get-ChildItem -Path ("$WorkDir\$VmFixed-$(Get-DateShort).*") -File
                    $BackupFileN = $BackupFile.name
                    $BackupFileNSplit = $BackupFileN.split(".")

                    $ShortDateT = Test-Path -Path $Backup\$BackupFileN

                    If ($ShortDateT)
                    {
                        Write-Log -Type Info -Evt "(VM:$Vm) File $BackupFileN already exists, appending number"
                        $FileExist = Get-ChildItem -Path $BackupFile -File
                        $i = 1
                        
                        If ($Null -eq $BackupFileNSplit[2])
                        {
                            $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++ + $FileExist.Extension)
                            $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                        }
                        else {
                            $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++ + "." + $BackupFileNSplit[1] + $FileExist.Extension)
                            $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                        }

                        If ($ShortDateExistT)
                        {
                            If ($Null -eq $BackupFileNSplit[2])
                            {
                                do {
                                    $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++ + $FileExist.Extension)
                                    $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                                } until ($ShortDateExistT -eq $false)
                            }
                            else {
                                do {
                                    $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++ + "." + $BackupFileNSplit[1] + $FileExist.Extension)
                                    $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                                } until ($ShortDateExistT -eq $false)
                            }
                        }

                        ## Move with shortdate and appened number
                        try {
                            Get-ChildItem -Path $BackupFile | Move-Item -Destination $Backup\$ShortDateNN -ErrorAction 'Stop'
                        }
                        catch{
                            $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                        }
                    }

                    ## Move with shortdate
                    try {
                        Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*.*" | Move-Item -Destination $Backup -ErrorAction 'Stop'
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                    }
                }
            }

            ## Move with long date
            else {
                try {
                    Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*.*" | Move-Item -Destination $Backup -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }
        }
    }

    ## -Compress switch is NOT configured and the -Keep switch is configured.
    ## Rename the export of each VM to include the date.
    else {
        If ($ShortDate)
        {
            $ShortDateT = Test-Path -Path ("$WorkDir\$VmFixed-$(Get-DateShort)")

            If ($ShortDateT)
            {
                Write-Log -Type Info -Evt "(VM:$Vm) File $VmFixed-$(Get-DateShort) already exists, appending number"
                $i = 1
                $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN

                If ($ShortDateExistT)
                {
                    do {
                        $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                        $ShortDateExistT = Test-Path -Path $WorkDir\$ShortDateNN
                    } until ($ShortDateExistT -eq $false)
                }

                try {
                    Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$ShortDateNN")
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }

            try {
                Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$VmFixed-$(Get-DateShort)")
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
            }
        }

        else {
            try {
                Get-ChildItem -Path $WorkDir -Filter $Vm -Directory | Rename-Item -NewName ("$WorkDir\$VmFixed-$(Get-DateLong)")
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
            }
        }

        ## If working directory has been configured by the user, move the backup to the backup folder and rename to include the date.
        If ($WorkDir -ne $Backup)
        {
            ## Make sure the backup directory exists.
            $BackupFolderT = Test-Path $Backup

            If ($BackupFolderT -eq $False)
            {
                Write-Log -Type Info -Evt "Backup directory $Backup doesn't exist. Creating it."
                New-Item $Backup -ItemType Directory -Force | Out-Null
            }

            If ($ShortDate)
            {
                $ShortDateT = Test-Path -Path ("$Backup\$VmFixed-$(Get-DateShort)")

                If ($ShortDateT)
                {
                    Write-Log -Type Info -Evt "(VM:$Vm) File $VmFixed-$(Get-DateShort) already exists, appending number"
                    $i = 1
                    $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                    $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN

                    ## If backup folder already exists with same name, append a number
                    If ($ShortDateExistT)
                    {
                        do {
                            $ShortDateNN = ("$VmFixed-$(Get-DateShort)-{0:D3}" -f $i++)
                            $ShortDateExistT = Test-Path -Path $Backup\$ShortDateNN
                        } until ($ShortDateExistT -eq $false)
                    }

                    ## Moving backup folder with shortdate and append number
                    try {
                        Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Move-Item -Destination $Backup\$ShortDateNN -ErrorAction 'Stop'
                    }
                    catch{
                        $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                    }
                }

                ## Moving backup folder with shortdate
                try {
                    Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*" -Directory | Move-Item -Destination ("$Backup\$VmFixed-$(Get-DateShort)") -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }

            ## Moving backup folder with longdate
            else {
                try {
                    Get-ChildItem -Path $WorkDir -Filter "$VmFixed-*-*-*_*-*-*" -Directory | Move-Item -Destination ("$Backup\$VmFixed-$(Get-DateLong)") -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }
        }
    }
}
##
## End of backup Options function
##

## Setting an easier to use variable for computer name of the Hyper-V server.
$Vs = $Env:ComputerName

## getting Windows Version info
$OSVMaj = [environment]::OSVersion.Version | Select-Object -expand major
$OSVMin = [environment]::OSVersion.Version | Select-Object -expand minor
$OSVBui = [environment]::OSVersion.Version | Select-Object -expand build
$OSV = "$OSVMaj" + "." + "$OSVMin" + "." + "$OSVBui"

## If a VM list file is configured, get the content of the file, otherwise just get the running VMs.
If ($VmList)
{
    $Vms = Get-Content $VmList
}

else {
    $Vms = Get-VM | Where-Object {$_.State -eq 'Running'} | Select-Object -ExpandProperty Name
}

## Check to see if there are any VMs to process.
## If there are no VMs, then do nothing.
If ($Vms.count -ne 0)
{
    ## If the user has not configured the working directory, set it as the backup directory.
    If ($Null -eq $WorkDir)
    {
        $WorkDir = "$Backup"
    }

    If ($Null -eq $ShortDate)
    {
        $ShortDate = "$LongDate"
    }

    If ($Null -ne $SzSwitches)
    {
        $SzSwSplit = $SzSwitches.split(",")
    }

    If ($Sz -eq $True)
    {
        $7zT = Test-Path "$env:programfiles\7-Zip\7z.exe"
    }

    ##
    ## Display the current config and log if configured.
    ##

    Write-Log -Type Conf -Evt "************ Running with the following config *************."
    Write-Log -Type Conf -Evt "Utility Version:.........21.11.09"
    Write-Log -Type Conf -Evt "Hostname:................$Vs."
    Write-Log -Type Conf -Evt "Windows Version:.........$OSV."
    Write-Log -Type Conf -Evt "VMs to backup:..........."

    ForEach ($Vm in $Vms)
    {
        Write-Log -Type Conf -Evt ".........................$Vm"
    }

    Write-Log -Type Conf -Evt "Backup directory:........$Backup."
    Write-Log -Type Conf -Evt "Working directory:.......$WorkDir."
    
    If ($Null -ne $History)
    {
        Write-Log -Type Conf -Evt "Backups to keep:.........$History days"
    }

    else {
        Write-Log -Type Conf -Evt "Backups to keep:.........No Config"
    }

    If ($Null -ne $LogPath)
    {
        Write-Log -Type Conf -Evt "Logs directory:..........$LogPath."
    }
    
    else {
        Write-Log -Type Conf -Evt "Logs directory:..........No Config"
    }
    
    If ($MailTo)
    {
        Write-Log -Type Conf -Evt "E-mail log to:...........$MailTo."
    }
    
    else {
        Write-Log -Type Conf -Evt "E-mail log to:...........No Config"
    }
    
    If ($MailFrom)
    {
        Write-Log -Type Conf -Evt "E-mail log from:.........$MailFrom."
    }
    
    else {
        Write-Log -Type Conf -Evt "E-mail log from:.........No Config"
    }
    
    If ($MailSubject)
    {
        Write-Log -Type Conf -Evt "E-mail subject:..........$MailSubject."
    }

    else {
        Write-Log -Type Conf -Evt "E-mail subject:..........Default"
    }

    If ($SmtpServer)
    {
        Write-Log -Type Conf -Evt "SMTP server:.............$SmtpServer."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP server:.............No Config"
    }

    If ($SmtpPort)
    {
        Write-Log -Type Conf -Evt "SMTP Port:...............$SmtpPort."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP Port:...............Default"
    }

    If ($SmtpUser)
    {
        Write-Log -Type Conf -Evt "SMTP user:...............$SmtpUser."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP user:...............No Config"
    }

    If ($SmtpPwd)
    {
        Write-Log -Type Conf -Evt "SMTP pwd file:...........$SmtpPwd."
    }

    else {
        Write-Log -Type Conf -Evt "SMTP pwd file:...........No Config"
    }

    Write-Log -Type Conf -Evt "-UseSSL switch:..........$UseSsl."
    Write-Log -Type Conf -Evt "-NoPerms switch:.........$NoPerms."
    Write-Log -Type Conf -Evt "-ShortDate switch:.......$ShortDate."
    Write-Log -Type Conf -Evt "-Compress switch:........$Compress."
    Write-Log -Type Conf -Evt "-Sz switch:..............$Sz."

    If ($Sz)
    {
        Write-Log -Type Conf -Evt "7-zip installed:.........$7zT."
    }

    If ($SzSwitches)
    {
        Write-Log -Type Conf -Evt "7-zip Options:...........$SzSwitches."
    }
    
    else {
        Write-Log -Type Conf -Evt "7-zip Options:...........Default."
    }

    Write-Log -Type Conf -Evt "************************************************************"
    Write-Log -Type Info -Evt "Process started."

    ##
    ## Display current config ends here.
    ##

    ##
    ## -NoPerms process starts here.
    ##

    ## If the -NoPerms switch is set, start a custom process to copy all the VM data.
    If ($NoPerms)
    {
        ForEach ($Vm in $Vms)
        {
            ## For 7zip, replace . dots with - hyphens in the vm name
            $VmFixed = $Vm.replace(".","-")
            $VmInfo = Get-VM -name $Vm

            ## Test for the existence of a previous VM export. If it exists, delete it.
            $VmExportBackupT = Test-Path "$WorkDir\$Vm"
            If ($VmExportBackupT -eq $True)
            {
                Remove-Item "$WorkDir\$Vm" -Recurse -Force
            }

            ## Create directories for the VM export.
            try {
                New-Item "$WorkDir\$Vm" -ItemType Directory -Force | Out-Null
                New-Item "$WorkDir\$Vm\Virtual Machines" -ItemType Directory -Force | Out-Null
                New-Item "$WorkDir\$Vm\VHD" -ItemType Directory -Force | Out-Null
                New-Item "$WorkDir\$Vm\Snapshots" -ItemType Directory -Force | Out-Null
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
            }

            #Check for VM running
            If (Get-VM win10 | Where-Object {$_.State -eq 'Running'})
            {
                Write-Log -Type Info -Evt "(VM:$Vm) Stopping VM"
                Stop-VM -Name $Vm
            }

            else {
                Write-Log -Type Err -Evt "(VM:$Vm) VM not running"
            }

            ##
            ## Copy the VM config files and log if there is an error.
            ##

            try {
                Write-Log -Type Info -Evt "(VM:$Vm) Copying config files"
                Copy-Item "$($VmInfo.ConfigurationLocation)\Virtual Machines\$($VmInfo.id)" "$WorkDir\$Vm\Virtual Machines\" -Recurse -Force
                Copy-Item "$($VmInfo.ConfigurationLocation)\Virtual Machines\$($VmInfo.id).*" "$WorkDir\$Vm\Virtual Machines\" -Recurse -Force
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
            }

            ##
            ## End of VM config files.
            ##

            ##
            ## Copy the VHDs and log if there is an error.
            ##

            try {
                Write-Log -Type Info -Evt "(VM:$Vm) Copying VHD files"
                Copy-Item $VmInfo.HardDrives.Path -Destination "$WorkDir\$Vm\VHD\" -Recurse -Force
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
            }

            ##
            ## End of VHDs.
            ##

            ## Get the VM snapshots/checkpoints.
            $Snaps = Get-VMSnapshot $Vm

            ForEach ($Snap in $Snaps)
            {
                ##
                ## Copy the snapshot config files and log if there is an error.
                ##

                try {
                    Write-Log -Type Info -Evt "(VM:$Vm) Copying Snapshot config files"
                    Copy-Item "$($VmInfo.ConfigurationLocation)\Snapshots\$($Snap.id)" "$WorkDir\$Vm\Snapshots\" -Recurse -Force
                    Copy-Item "$($VmInfo.ConfigurationLocation)\Snapshots\$($Snap.id).*" "$WorkDir\$Vm\Snapshots\" -Recurse -Force
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }

                ##
                ## End of snapshot config.
                ##

                ## Copy the snapshot root VHD.
                try {
                    Write-Log -Type Info -Evt "(VM:$Vm) Copying Snapshot root VHD files"
                    Copy-Item $Snap.HardDrives.Path -Destination "$WorkDir\$Vm\VHD\" -Recurse -Force -ErrorAction 'Stop'
                }
                catch{
                    $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
                }
            }

            Write-Log -Type Info -Evt "(VM:$Vm) Starting VM"
            Start-VM $Vm
            Start-Sleep -S 60
            OptionsRun
        }
    }

    ##
    ## -NoPerms process ends here.
    ##
    ##
    ## Standard export process starts here.
    ##

    ## If the -NoPerms switch is NOT set, for each VM check for the existence of a previous export.
    ## If it exists then delete it, otherwise the export will fail.
    else {
        ForEach ($Vm in $Vms)
        {
            ## For 7zip, replace . dots with - hyphens in the vm name
            $VmFixed = $Vm.replace(".","-")

            $VmExportBackupT = Test-Path "$WorkDir\$VmFixed"
            If ($VmExportBackupT -eq $True)
            {
                Remove-Item "$WorkDir\$VmFixed" -Recurse -Force
            }

            If ($WorkDir -ne $Backup)
            {
                $VmExportWDT = Test-Path "$Backup\$VmFixed"
                If ($VmExportWDT -eq $True)
                {
                    Remove-Item "$Backup\$VmFixed" -Recurse -Force
                }
            }
        }

        ## Do a regular export of the VMs.
        ForEach ($Vm in $Vms)
        {
            ## For 7zip, replace . dots with - hyphens in the vm name
            $VmFixed = $Vm.replace(".","-")

            try {
                Write-Log -Type Info -Evt "(VM:$Vm) Attempting to export VM"
                $Vm | Export-VM -Path "$WorkDir" -ErrorAction 'Stop'
            }
            catch{
                $_.Exception.Message | Write-Log -Type Err -Evt "(VM:$Vm) $_"
            }
        }

        ## Run the configuration options on the above backup files and folders.
        ForEach ($Vm in $Vms)
        {
            ## For 7zip filename, replace . dots with - hyphens in the vm name
            $VmFixed = $Vm.replace(".","-")
            OptionsRun
        }
    }

    ##
    ## End of standard export block
    ##
}

## If there are no VMs running, then do nothing.
else {
    Write-Log -Type Err -Evt "There are no VMs running to backup"
}

Write-Log -Type Info -Evt "Process finished."

## If logging is configured then finish the log file.
If ($LogPath)
{
    Add-Content -Path $Log -Encoding ASCII -Value "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") [INFO] Log finished"

    ## This whole block is for e-mail, if it is configured.
    If ($SmtpServer)
    {
        ## Default e-mail subject if none is configured.
        If ($Null -eq $MailSubject)
        {
            $MailSubject = "Hyper-V Backup Utility Log"
        }

        ## Default Smtp Port if none is configured.
        If ($Null -eq $SmtpPort)
        {
            $SmtpPort = "25"
        }

        ## Setting the contents of the log to be the e-mail body.
        $MailBody = Get-Content -Path $Log | Out-String

        ## If an smtp password is configured, get the username and password together for authentication.
        ## If an smtp password is not provided then send the e-mail without authentication and obviously no SSL.
        If ($SmtpPwd)
        {
            $SmtpPwdEncrypt = Get-Content $SmtpPwd | ConvertTo-SecureString
            $SmtpCreds = New-Object System.Management.Automation.PSCredential -ArgumentList ($SmtpUser, $SmtpPwdEncrypt)

            ## If -ssl switch is used, send the email with SSL.
            ## If it isn't then don't use SSL, but still authenticate with the credentials.
            If ($UseSsl)
            {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -UseSsl -Credential $SmtpCreds
            }

            else {
                Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort -Credential $SmtpCreds
            }
        }

        else {
            Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailBody -SmtpServer $SmtpServer -Port $SmtpPort
        }
    }
    ## End of Email block
}

## End