-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvert-VMGeneration.ps1
More file actions
2210 lines (1927 loc) · 119 KB
/
Convert-VMGeneration.ps1
File metadata and controls
2210 lines (1927 loc) · 119 KB
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
#
# ---------------------------------------------------------------------------------------------------------------------------
#
# http://code.msdn.microsoft.com/ConvertVMGeneration
# See the above site for license terms (Microsoft Limited Public License, MS-LPL)
#
# By: John Howard - Program Manager, Hyper-V Team
# - Prototype & Bulk of code [http://blogs.technet.com/jhoward]
#
# Stefan Wernli, Brian Young - Developers, Hyper-V Team
# - Gave me lots of invaluable assistance. Thank you! :)
#
# Originally Created: May - October 2013
#
# About: Script for converting a Hyper-V virtual machine from generation 1 to generation 2.
# This script is not endorsed or supported by Microsoft Corporation.
#
# Requires: Windows 8.1/Windows Server 2012 R2 with Hyper-V enabled as machine to run this script on
# Windows 8/8.1 (64-bit)/Windows Server 2012 or 2012 R2 as VM being converted to Generation 2
#
# History: 23rd Oct 2013, Version 1.01 - First public release
# 31st Oct 2013, Version 1.02 - Additional trace points (make it easier to debug user reported problems)
# - Cache avoidance for new version check
# - Fixed bug where single partition source boot disk (eg using Convert-WindowsImage)
# 5th Nov 2013, Version 1.03 - Additions to tracing. In particular to catch a couple of reported exceptions
# 6th Dec 2013, Version 1.04 - Fixed exception in networking cloning
# - Additional tracing and logging
#
# ---------------------------------------------------------------------------------------------------------------------------
#
# Future improvements to consider: (Just keeping a list somewhere handy)
#
# - Have parameter set including VM object http://technet.microsoft.com/en-us/library/hh847743.aspx
# - Check for enough disk space before running the capture or apply
# - Better handling of SCSI locations with multiple originating VM SCSI controllers. Including support for >64 devices.
# - Handle FibreChannelConnection and FibreChannelPort resource pools. If anyone asks...
#
# ---------------------------------------------------------------------------------------------------------------------------
#
<#
.SYNOPSIS
Converts a Hyper-V generation 1 Windows based virtual machine to generation 2
By John Howard, Hyper-V Team, Microsoft Corporation. (c) 2013.
Please leave feedback on the home page for this utility if you find it useful (link below). Thank you :)
.LINK
http://blogs.technet.com/jhoward (Author blog)
.LINK
http://code.msdn.microsoft/ConvertVMGeneration
.DESCRIPTION
Generation 2 virtual machines were introduced in Hyper-V for Windows 8.1 and Windows Server 2012 R2.
There is no in-box capability in Hyper-V to convert a generation 1 virtual machine to a generation 2
virtual machine. To manually convert, it would generally be necessary to install a new guest operating
system instance, and migrate application settings across. Alternately, assuming the guest operating
system can run in a generation 2 virtual machine, a manual conversion can be performed.
This cmdlet automates the conversion process. The process is done in three phases, each of which
can be performed seperately if desired using the -Action parameter.
During the conversion process, this cmdlet leaves the source generation 1 virtual machine intact. However,
you should ensure that once converted, both virtual machines are not started simultaneously as, for example,
they may be attempting to access the same data disks; both appear to be the same machine from the network.
Windows Recovery Environment (WinRE) and Push Button Reset (PBR) are not migrated. See parameters
-IgnoreWinRE and -IgnorePBR for more information.
There are a number of features which are not migrated to the generation 2 virtual machine. Some due to
devices differences between generation 1 and generation 2 virtual machines; some due to no API support;
some due to my time when creating this script. A non-exhaustive list is below:
- COM ports; Floppy; Empty and physical DVD drives; Legacy Network Adapters; RemoteFX; .VHD disks are skipped.
- VMs with checkpoints cannot be converted
- VMs with multiple windows partitions on the source boot disk cannot be converted
- Additional data partitions on the source boot disk are not converted (although additional disks are)
- 32-bit guest operating systems cannot be converted
- Windows operating systems prior to Windows 8/Windows Server 2012 cannot be converted
- Non-Windows operating systems cannot be converted (although other tools may exist)
- Resource metering is not carried across to the converted virtual machine
IMPORTANT
---------
During the conversion process, there is one highly destructive operation which entails deleting all
data on a disk (the VHDX used as the boot disk for the generation 2 virtual machine). As this is such
a destructive operation, and there is always a risk of a coding error, there is a prompt to confirm
this operation. Further, against PowerShell guidelines, this prompt cannot be suppressed. This is a
conscious design choice rendering this script unsuitable for batch usage.
.EXAMPLE
.\Convert-VMGeneration.ps1 -VMName "Convert me" -Path C:\ClusterStorage\Volume1
Converts a generation 1 virtual machine named 'Convert me'. The result will be the creation
of a virtual machine 'Convert me (Generation 2)' with a new boot disk.
.EXAMPLE
.\Convert-VMGeneration.ps1 -VMName "Convert me" -VHDXSizeGB 40
Converts a generation 1 virtual machine named 'Convert me'. The result will be the creation
of a virtual machine 'Convert me (Generation 2)' with a new boot disk of size 40GB. This
will fail if there is not enough space to fit the contents into the new VHDX.
.EXAMPLE
.\Convert-VMGeneration.ps1 -VMName "Convert me" -OverwriteVM -OverwriteVHDX -OverwriteWIM -WIM "c:\interim.wim" -KeepWIM
Converts a generation 1 virtual machine named 'Convert me' to a generation 2 virtual machine
named 'Convert me (Generation 2)'. In this example, if the interim .WIM file, the new boot disk
for the generation 2 virtual machine, or the virtual machine 'Convert me (Generation 2)' exists,
they will be overwritten.
.EXAMPLE
.\Convert-VMGeneration.ps1 -VMName "Convert me" -Action Capture -WIM "c:\storage\captured.wim" -OverwriteWIM
Captures the boot disk of a generation 1 virtual machine named 'Convert me' into
c:\storage\captured.wim, which already exists and should be overwritten.
.PARAMETER VMName
The name of the virtual machine to be converted from generation 1 to generation 2.
Required for All, Capture and Clone Actions.
Optional for Apply action. If not present, -TargetVHDSizeGB must be supplied.
.PARAMETER Action
Defines what phase of the conversion process this script will perform.
Capture - Capture the Windows partition of the boot VHD(X) from a generation 1 virtual machine to a WIM
Apply - Applies the WIM to a boot VHDX for a generation 2 virtual machine and makes it bootable
Clone - Creates a generation 2 VM using the configuration template from a generation 1 virtual machine
All - Default action. Performs all the above in one pass in the order Capture, Apply, Clone
.PARAMETER Path
If supplied, this is used as the path in which to create the generation 2 virtual machine. By
default, the path will be the same path as the source generation 1 virtual machine. It is
recommended that this parameter is used.
.PARAMETER NoVersionCheck
If present, this script will not look for a newer version of this script being available
.PARAMETER NoPSVersionCheck
If present, no validation on the version of PowerShell is made. It is not recommended that this is
used, and only Windows PowerShell in Windows 8.1 and Windows Server 2012 R2 has been tested.
.PARAMETER Quiet
If present, informational output will be suppressed. Warnings, errors and a summary will not be suppressed.
.PARAMETER IgnoreWinRE
If present, this script will not stop if Windows Recovery Environment (WinRE) is configured on the
source virtual machine. It will be necessary to reconfigure WinRE in the target virtual machine
after it has been created. It is strongly recommended that prior to conversion, WinRE is disabled
in the source VM by running 'reagentc /disable' from an elevated command prompt. In the target VM,
re-enable by running 'reagentc /enable' from an elevated command prompt.
.PARAMETER IgnorePBR
If present, this script will not stop if Push Button Reset is configured in the virtual machine.
This script ignores OS recovery partitions during the conversion process. It will be necessary to
manually reconfigure PBR in the generation 2 VM if desired. Note that this is not generally an
issue in a virtual machine environment as PBR is not usually configured.
More information can be found at http://technet.microsoft.com/library/jj126997.aspx
.PARAMETER VHDXSizeGB
If supplied, this is the size in GB of the newly created boot disk for use in the generation 2
virtual machine. It must be between 1 and 64. If it is not supplied, the generation 2 boot VHDX
size is calculated based on the size of the Windows partition in the source VMs boot disk,
combined with the size of other partitions necessary to support booting in a generation 2 virtual
machine, and a WinRE partition. Making this size too small may mean that this script will fail.
.PARAMETER VHDX
Full file path to the VHDX to be used by the generation 2 virtual machine. By default, this script
will create a new VHDX with the same name and path as the boot disk on the generation 1 virtual machine,
appending '(Generation 2)' to the name.
.PARAMETER OverwriteVHDX
If supplied, this script will not stop when attempting to create the VHDX for the boot disk of the
generation 2 virtual machine if it already exists.
.PARAMETER WIM
Full file path to the WIM file containing a captured image of the generation 1 virtual machines
boot disk Windows partition. By default, this script will create the WIM file in the %TEMP%
directory. Use this parameter if you do not have enough diskspace in the %TEMP% directory, or
intend to keep an archive as a time-saver for cloning.
.PARAMETER KeepWIM
If supplied, the WIM file will not be deleted after it is applied to the converted generation 2
virtual machine.
.PARAMETER OverwriteWIM
If supplied, this script will not stop when attempting to create the WIM file containing an image
of the Windows partition on the boot disk of the generation 1 virtual machine if it already exists.
.PARAMETER OverwriteVM
If supplied, this script will not stop when attempting to create the generation 2 virtual machine
if it already exists.
.PARAMETER NewVMName
If supplied, this is the name used to create the generation 2 virtual machine. By default, the
new virtual machine has the same name as the source generation 1 virtual machine, appended with
'(Generation 2)'.
.PARAMETER IgnoreReplicaCheck
If supplied, this script will ignore the check to determine if the generation 1 virtual machine
has Hyper-V Replica enabled for it. This is experimental - I have done no validation that this
script works when replica is enabled.
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="High")]
param
(
# Name of the VM
# Removed [parameter(Mandatory=$true)] for the following reason:
# If the action is apply, the only reason we would need the source VM is to find the boot disk so that subsequently we can find the size of the
# Windows partition on it, so we can throw that into the calculation for the size of the target VHDX. However, as we have an explicit parameter
# for the size of the target, if that is supplied on Apply, we don't need the originating VM name.
[string] [ValidateNotNullOrEmpty()] [alias("Name")] $VMName="",
# What this script is going to do
[string] [ValidateSet("Capture", "Apply", "Clone", "All")] $Action="All",
# Path of new VM (otherwise defaults to same path as source VM)
[string]$Path="",
# Check for later version
[switch] $NoVersionCheck=$False,
# Check for correct version of PS
[switch] $NoPSVersionCheck=$False,
# To be quiet in output (banners for example)
[switch] $Quiet=$False,
# Ignore if RE is configured. In Capture and All (validated seperately)
[switch] $IgnoreWinRE=$False,
# Ignore if PBR is configured. In Capture and All (validated seperately)
[switch] $IgnorePBR=$False,
# Size of the new VHDX to be created. In Apply and All (validated seperately)
[int32] [ValidateRange(1,64)] $VHDXSizeGB=0,
# Name of the VHDX captured from the source and to boot the target VM. In Apply, Clone and All (validate seperately)
[string] $VHDX="",
# Whether to overwrite the VHDX. In Capture and All (validated seperately)
[switch]$OverwriteVHDX=$False,
# Name of the WIM to use. In Capture, Apply and All (validated seperately)
# - In Apply, the WIM must exist.
# - In Apply or Capture, KeepWIM defaulted to True
[string] $WIM="",
# Whether to keep the WIM after it's been used. In Apply and All (validated seperately)
[switch] $KeepWIM=$False,
# Whether to overwrite the WIM if it already exists. In Capture and All (validated seperately)
[switch] $OverwriteWIM=$False,
# Whether to overwrite the VM. In Clone and All (validated seperately)
[switch]$OverwriteVM=$False,
# Name of new VM (otherwise defaults to name of source VM plus "(generation 2)"
[string] $NewVMName="",
# To ignore the check for replica. Experimental
[switch] $IgnoreReplicaCheck
)
# Make life a little more challenging.... All goodness though :)
Set-PSDebug -Strict
Set-StrictMode -Version latest
$script:Version = "1.04" # Version number of this script
$script:LastModified = "6th Dec 2013" # Last modified date of this script
$script:TargetBootDiskMounted = $False # Is the target VMs boot disk mounted?
$script:TargetDriveLetterESP = "" # Drive letter allocated to the ESP on the target disk
$script:TargetDriveLetterWindows = "" # Drive letter allocated to the Windows partition on the target disk
$script:TargetDriveESPConfigured = $False # Set to true once diskpart has been run on new VHDX
$script:SourceVMObject = $Null # Represents the VM being migrated to generation 1
$script:SourceBootDiskMounted = $False # Is the source VMs boot disk mounted?
$script:SourceBootDiskPath = "" # From Get-VMDiskDrive for source boot disk
$script:SourceBootDiskWindowsPartition = $Null # The partition on source VM boot disk containing Windows installation to migrate
$script:SourceBootDiskWindowsPartitionNum = -1 # The partition number of above. Only used for summary message, not for procesing.
$script:SourceBootDiskWindowsPartitionUsed = 0 # The bytes used on the source windows partition.
$script:CleanupCalled = $False # To stop re-entrant calls to cleanup()
$script:WarningCount = 0 # Number of warnings found as we went along
$script:ReachedEndOfProcessing = $False # Have we got to the end of everythign
$script:TestHookBCDBootWindowsDrive = "" # Just a test hook. Nothing to see here, move along please...
$script:TestHookIgnoreParameterChecks = $False # Same deal as above.
[int32]$script:ProgressPoint = 0 # For tracking exit point
# ---------------------------------------------------------------------------------------------------------------------------
# Function to output progress
# ---------------------------------------------------------------------------------------------------------------------------
Function Write-Info ($info) { if (!$Quiet){ Write-Host "INFO: $info" } }
# ---------------------------------------------------------------------------------------------------------------------------
# Function to cleanup everything when we're going to be quitting
# ---------------------------------------------------------------------------------------------------------------------------
Function Cleanup([string] $sDetail) {
# Only as I put cleanup() in the main finally block of code to absolutely make sure we clean up regardless
if ($script:cleanupcalled) {
Write-Verbose "Exiting cleanup as already called"
exit
}
$script:CleanupCalled = $True
if ($sDetail.Length) { Write-Host -ForegroundColor Red ("`n" + $sDetail + "`n") }
if (($script:SourceBootDiskMounted -eq $True) -and (($script:SourceBootDiskPath).Length)) {
Write-Verbose ("Cleanup - unmounting " + ($script:SourceBootDiskPath))
Dismount-DiskImage ($script:SourceBootDiskPath) -ErrorAction SilentlyContinue
if (!$?) { Write-Error ("Failed to unmount "+ ($script:SourceBootDiskPath) + "`n"+ $Error[0][0]) }
} else { Write-Verbose "Source was not mounted so not cleaning up" }
if ($script:TargetBootDiskMounted -eq $True) {
Write-Verbose "Cleanup - Unmounting the converted VHDX"
# Workaround for bug where the ESP drive letter is leaked if the disk is unmounted without releasing the access path
if ($script:TargetDriveLetterESP -ne "") {
if ($script:TargetDriveESPConfigured -eq $True) {
Write-Verbose ("TargetDriveLetterESP is " + ($script:TargetDriveLetterESP))
Write-Verbose ("VHDX is " + ($VHDX))
$DiskImage = (Get-DiskImage $VHDX )
Write-Verbose ("DiskImage | Get-Disk is " + ($DiskImage | Get-Disk ))
Write-Verbose ("DiskImage | Get-Disk Number is " + (($DiskImage | Get-Disk ).Number))
Remove-PartitionAccessPath -disknumber (($DiskImage | Get-Disk).Number) `
-PartitionNumber 3 `
-AccessPath $script:TargetDriveLetterESP `
-ErrorAction SilentlyContinue
if (!$?) { Write-Error ("Failed to remove drive letter "+ $script:TargetDriveLetterESP + "`n"+ $Error[0][0]) }
else { Write-Verbose "Called Remove-PartitionAccessPath OK" }
} else { Write-Verbose "ESP is not configured" }
} else { Write-Verbose "No target drive letter for ESP" }
Write-Verbose ("Unmounting "+$VHDX)
Dismount-DiskImage $VHDX -erroraction SilentlyContinue
if (!$?) { Write-Error ("Failed to unmount "+ $VHDX + "`n"+ $Error[0][0]) }
} else { Write-Verbose "Target was not mounted so not cleaning up" }
# Delete (or retain) the WIM depending on user selection
$WIMDeleted = $False
if ($WIM -ne "") {
if (!($KeepWIM)) {
if (Test-Path $WIM) {
Write-Verbose "Deleting captured image..."
Remove-Item $WIM -ErrorAction SilentlyContinue
if (!$?) { Write-Error ("Failed to remove WIM "+ $WIM + "`n"+ $Error[0][0]) }
$WIMDeleted = $True
} else {
Write-Verbose ($WIM + " does not exist so not deleting")
}
} else {
Write-Verbose ("WIM file " + $WIM + " retained")
}
} else { Write-Verbose "Don't have a WIM file to consider deleting" }
Write-Verbose "Checking latest version"
if (!$NoVersionCheck) {
if (-3 -eq (Check-LatestVersion "http://blogpics.dyndns.org/Convert-VMGeneration.txt")) {
$lvcheck = (Check-LatestVersion "http://blogs.technet.com/jhoward/pages/convertvmgenerationlatestversion.aspx")
}
}
# All complete message.
if ($sDetail.Length -eq 0) {
if ($script:ReachedEndOfProcessing) {
Write-Host ""
Write-Host -ForegroundColor Yellow "SUMMARY:"
switch ($script:Action) {
"Capture" { Write-Host -ForegroundColor Yellow ("· Image file '" + $WIM + "' was created.")
Write-Host -ForegroundColor Yellow ("· Image contains partition " + $script:SourceBootDiskWindowsPartitionNum + " from '" + $script:SourceBootDiskPath + "' attached to virtual machine '" + $VMName + "'.")
}
"Apply" { Write-Host -ForegroundColor Yellow ("· '" + $VHDX + "' was created")
Write-Host -ForegroundColor Yellow ("· The contents of '" + $script:WIM + "' was applied to the Windows partition." )
if ($WIMDeleted) { Write-Host -ForegroundColor Yellow ("· WIM has been deleted (-KeepWIM to retain)." ) }
}
"Clone" { Write-Host -ForegroundColor Yellow ("· Virtual machine '" + $NewVMName + "' was created.")
Write-Host -ForegroundColor Yellow ("· Boot disk is '" + $VHDX + "'.")
Write-Host -ForegroundColor Yellow ("· Configuration was cloned from VM '" + $VMName + "'." )
}
"All" { Write-Host -ForegroundColor Yellow ("· Virtual machine '" + $NewVMName + "' was created.")
Write-Host -ForegroundColor Yellow ("· Boot disk is '" + $VHDX + "'.")
Write-Host -ForegroundColor Yellow ("· Configuration was cloned from VM '" + $VMName + "'." )
if (!($WIMDeleted)) {
Write-Host -ForegroundColor Yellow ("· Image file '" + $WIM + "' has been retained." )
Write-Host -ForegroundColor Yellow ("· Image contains partition " + $script:SourceBootDiskWindowsPartitionNum + " from '" + $script:SourceBootDiskPath + "'.")
}
}
}
}
Write-Host ""
if ($script:ReachedEndOfProcessing) {
if ($script:WarningCount -gt 0) {
if ($script:WarningCount -gt 1) {
Write-Warning ("Completed with $script:WarningCount warnings. Trace status code " + $script:ProgressPoint)
} else {
Write-Warning ("Completed with $script:WarningCount warning. Trace status code " + $script:ProgressPoint)
}
} else {
Write-Info ("Complete.")
}
} else {
$script:ProgressPoint += 100000
Write-Host -ForegroundColor Cyan ("Terminated early. Trace status code " + $script:ProgressPoint)
}
} else { Write-Host -ForegroundColor Red ("Completed with error. Trace status code " + $script:ProgressPoint) }
if ($script:ProgressPoint -gt 100000) { $script:ProgressPoint -= 100000 } # Just in case (added above)
if (($script:ProgressPoint -ge 90000) -and ($sDetail.Length)) {
Write-Host -Foregroundcolor Cyan "--------------------------------------------------------------------------------------"
Write-Host -Foregroundcolor Cyan "An exception occurred. Please report this bug by going to the home-page for this tool,"
Write-Host -Foregroundcolor Cyan "selecting the 'Q and A' tab and starting a new question. In the report, please post"
Write-Host -Foregroundcolor Cyan "the full output above showing the command line used. It would be useful too to post"
Write-Host -Foregroundcolor Cyan "configuration information about the VM being converted such as number of disks, "
Write-Host -Foregroundcolor Cyan "operating system, disk partition layout on the boot disk and anything else you think"
Write-Host -Foregroundcolor Cyan "may be pertinent and helpful. Thank you for making this utility better!`n"
Write-Host -Foregroundcolor Cyan ("Trace status code: " + $script:ProgressPoint)
Write-Host -Foregroundcolor Cyan "--------------------------------------------------------------------------------------"
}
Write-Verbose ("Calling exit from cleanup " + $script:ProgressPoint)
exit
}
# ---------------------------------------------------------------------------------------------------------------------------
# Function to perform additional parameter validation
# ---------------------------------------------------------------------------------------------------------------------------
Function Validate-Parameters {
try {
# Additional parameter validation. I do this here as, for example, a [switch] parameter, the .IsPresent attribute
# is always $True in a [ValidateScript] code block. Generally gave up in the end with the use of any [ValidateScript] for consistency.
# See Parameter Validation spreadsheet for more info on the code in this function (that's a comment for me BTW...)
Write-Verbose (">>Validate-Parameters")
$script:ProgressPoint = 100
# >>>>> Important: Do the things which change KeepWIM first to avoid accidental cleanup which deletes the WIM!
# KeepWIM can only be supplied in Capture, Apply and All.
if ($KeepWIM.GetType().name -eq "SwitchParameter") {
if (($KeepWIM.IsPresent) -and (($Action -ne "Capture") -and ($Action -ne "Apply") -and ($Action -ne "All"))) { Cleanup "-KeepWIM not valid with action '$Action'" }
} else {
if (($KeepWIM) -and (($Action -ne "Capture") -and ($Action -ne "Apply") -and ($Action -ne "All"))) { Cleanup "-KeepWIM not valid with action '$Action'" }
}
# KeepWIM is set to true if just capturing (otherwise it's a bit silly....)
if ($Action -eq "Capture") { $script:KeepWIM = $true }
# KeepWIM is set to true if user specified WIM during Apply or Capture (otherwise we use a temporary WIM file)
# Do this AFTER any checks which rely on $KeepWim.IsPresent
if (($WIM.Length) -and (($Action -eq "Apply") -or ($Action -eq "Capture"))) { $script:KeepWIM = $true }
# >>>>> Important: Do the things which change KeepWIM first to avoid accidental cleanup which deletes the WIM!
# VMName is mandatory for Clone, Capture, All. Mandatory for Apply if VHDXSizeGB is not specified, otherwise optional.
if (($Action -eq "Apply") -and ($VHDXSizeGB -eq 0) -and ($VMName -eq "")) { Cleanup "-VMName or -VHDXSizeGB must be supplied with action '$Action'" }
if (($Action -ne "Apply") -and ($VMName -eq "")) { Cleanup "-VMName must be supplied with action '$Action'" }
# IgnoreWinRE. Only valid in Capture and All
if ($IgnoreWinRE.GetType().name -eq "SwitchParameter") {
if (($IgnoreWinRE.IsPresent) -and (($Action -ne "capture") -and ($Action -ne "all"))) { CleanUp "-IgnoreWinRE not valid with action '$Action'" }
} else {
if (($IgnoreWinRE) -and (($Action -ne "capture") -and ($Action -ne "all"))) { CleanUp "-IgnoreWinRE not valid with action '$Action'" }
}
# IgnorePBR. Only valid in Capture and All
if ($IgnorePBR.GetType().name -eq "SwitchParameter") {
if (($IgnorePBR.IsPresent) -and (($Action -ne "capture") -and ($Action -ne "all"))) { CleanUp "-IgnorePBR not valid with action '$Action'" }
} else {
if (($IgnorePBR) -and (($Action -ne "capture") -and ($Action -ne "all"))) { CleanUp "-IgnorePBR not valid with action '$Action'" }
}
# VHDXSizeGB can only be supplied in Apply and All. We already have validated the range.
if (($VHDXSizeGB -ne 0) -and (($Action -ne "Apply") -and ($Action -ne "All"))) { Cleanup "-VHDXSizeGB not valid with action '$Action'" }
# VMName should not be present in apply if VHDXSizeGB is supplied
if (($VHDXSizeGB -ne 0) -and ($Action -eq "Apply") -and ($VMName -ne "")) { Cleanup "-VMName cannot be specified with action '$Action' when -VHDXSizeGB is specified" }
# VHDX can only be supplied in Apply, Clone and All.
if (($VHDX.Length) -and (($Action -ne "Apply") -and ($Action -ne "Clone") -and ($Action -ne "All"))) { Cleanup "-VHDX not valid with action '$Action'" }
# VHDX must be supplied in Apply if VMName is not supplied
if (($Action -eq "Apply") -and ($VHDX -eq "") -and ($VMName -eq "")) { Cleanup "-VHDX must be specified with action '$Action' when -VMName is not specified"}
# VHDX must not exist if supplied in Apply and All unless OverwriteVHDX is also supplied.
if (($VHDX.Length) -and `
(!($OverwriteVHDX)) -and `
(($Action -eq "Apply") -or ($Action -eq "All")) -and `
(Test-Path $VHDX) ) { Cleanup "$VHDX exists. Use -OverwriteVHDX or supply a different VHDX filename" }
# VHDX must exist if supplied in Clone
if (($VHDX.Length) -and ($Action -eq "Clone") -and (!(Test-Path $VHDX))) { Cleanup "$VHDX not found" }
# OverwriteVHDX can only be supplied in Apply and All.
if ($OverwriteVHDX.GetType().name -eq "SwitchParameter") {
if (($OverwriteVHDX.IsPresent) -and (($Action -ne "Apply") -and ($Action -ne "All"))) { Cleanup "-OverwriteVHDX not valid with action '$Action'" }
} else {
if (($OverwriteVHDX) -and (($Action -ne "Apply") -and ($Action -ne "All"))) { Cleanup "-OverwriteVHDX not valid with action '$Action'" }
}
# WIM can only be supplied with Capture, Apply and All.
if (($WIM.Length) -and (($Action -ne "Capture") -and ($Action -ne "Apply") -and ($Action -ne "All"))) { Cleanup "-WIM not valid with action '$Action'" }
# WIM must exist if requesting an Apply operation
if (($WIM.Length) -and ($Action -eq "Apply") -and (!(Test-Path $WIM))) { Cleanup "$WIM could not be found" }
# WIM must not exist if supplied in Capture or All unless OverwriteWIM is also supplied.
if (($WIM.Length) -and `
(!($OverwriteWIM)) -and `
(($Action -eq "Capture") -or ($Action -eq "All")) -and `
(Test-Path $WIM) ) { Cleanup "$WIM exists. Use -OverwriteWIM or supply a different WIM filename" }
# WIM must be supplied on an Apply action
if (($WIM.Length -eq 0) -and ($Action -eq "Apply")) { Cleanup "-WIM must be specified with action '$Action'" }
# OverwriteWIM can only be supplied in Capture and All
if ($OverwriteWIM.GetType().name -eq "SwitchParameter") {
if (($OverwriteWIM.IsPresent) -and (($Action -ne "Capture") -and ($Action -ne "All"))) { Cleanup "-OverwriteWIM not valid with action '$Action'" }
} else {
if (($OverwriteWIM) -and (($Action -ne "Capture") -and ($Action -ne "All"))) { Cleanup "-OverwriteWIM not valid with action '$Action'" }
}
# OverwriteVM can only be supplied in Clone and All
if ($OverwriteVM.GetType().name -eq "SwitchParameter") {
if (($OverwriteVM.IsPresent) -and (($Action -ne "Clone") -and ($Action -ne "All"))) { Cleanup "-OverwriteVM not valid with action '$Action'" }
} else {
if (($OverwriteVM) -and (($Action -ne "Clone") -and ($Action -ne "All"))) { Cleanup "-OverwriteVM not valid with action '$Action'" }
}
# NewVMName can only be supplied with Clone and All.
if (($NewVMName.Length) -and (($Action -ne "Clone") -and ($Action -ne "All"))) { Cleanup "-NewVMName not valid with action '$Action'" }
# Path can only be supplied with Clone and All
if (($Path.Length) -and (($Action -ne "Clone") -and ($Action -ne "All"))) { Cleanup "-Path not valid with action '$Action'" }
Write-Verbose ("<< Validate-Parameters")
$script:ProgressPoint = 197
}
Catch [Exception] {
$script:ProgressPoint += 90000
Write-Host -ForegroundColor Red ("Exception in Validate-Parameters: " + $_.Exception.ToString())
Cleanup ("Exception in Validate-Parameters")
}
Finally {
Write-Verbose "<< Validate-Parameters()"
}
}
# ---------------------------------------------------------------------------------------------------------------------------
# Function to get value of an item from an XML Document
# ---------------------------------------------------------------------------------------------------------------------------
Function GetTag([System.Xml.XmlDocument] $Document, [String] $Item) {
Try {
$Nodes = $Document.SelectNodes("/Version/$Item")
if (0 -eq $Nodes.Count) {
Write-Verbose ("Zero nodes for item $Item")
return ""
}
Write-Verbose ("Value of $item is "+ $Nodes.value)
return $Nodes.value
} catch [Exception] { # Clone catch
Write-Host -ForegroundColor Red "ERROR: Exception in GetTag()"
Write-Host -ForegroundColor Red $_.Exception.ToString()
return ""
}
}
# ---------------------------------------------------------------------------------------------------------------------------
# Function to check for the latest version of this script
# ---------------------------------------------------------------------------------------------------------------------------
Function Check-LatestVersion($URL) {
# Returns: -3 if an error occurs (URL retrieval error, invalid content, other exception etc.)
# -2 if the version of this script is newer than what the web says. This probably means I'm developing
# -1 if a newer version is available.
# 0 if this is the latest version available.
#Example:
# <?xml version='1.0'?>
# <Latest value="5.67"/>
# <Date value="18th Oct 2013"/>
# <URL value="http://tinyurl.com/TBD"/>
# <Type value="Release Candidate"/>
# <About value="Some more information about it here"/>
# </Version>
Try {
$URL = $URL + "?v=" + $script:Version + "&p=" + $script:ProgressPoint + "&a=" + $Action + "&c=" + [string]([guid]::NewGuid()) # Avoid cache
# Try to get the Base64 encoded string containing the XML for the version. I only encode it as the
# blog site escapes everything if a post contains just XML. It's pretty horrible.
Try { $WebCall = (Invoke-WebRequest -URI $URL -UserAgent ("Mozilla/4.0+(compatible);") -ErrorAction SilentlyContinue) }
Catch [Exception] {
Write-Verbose ("Failed to get " + $URL + ". Error`n" + $Error[0][0])
return -3
}
Write-Verbose ("WebCall Content`n" + $WebCall.Content)
# Is is wrapped between "STARTLATESTVERSION" and "ENDLATESTVERSION"? (It will be for the blog site)
if ($WebCall.content.length -gt 0) {
if (($WebCall.Content.Contains("STARTLATESTVERSION")) -and ($WebCall.Content.Contains("ENDLATESTVERSION"))) {
Write-Verbose "Is wrapped between START and END LATESTVERSION tags"
$StartTag = $WebCall.Content.IndexOf("STARTLATESTVERSION")
$EndTag = $WebCall.Content.IndexOf("ENDLATESTVERSION")
$Base64 = $WebCall.content.substring($StartTag+18,$EndTag-$StartTag-18)
Write-Verbose ("Extracted base64 content is " + $Base64)
} else {
Write-Verbose "Is not wrapped so assuming this is the base64 itself"
$Base64 = $WebCall.Content
}
}
# Unencode it back to XML
Try { $XML = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($Base64)) }
Catch [Exception] {
Write-Verbose ("Failed to un-encode the content from " + $URL + ". Error`n" + $Error[0][0])
return -3
}
Write-Verbose ("XML obtained`n" + $XML)
# Need an XML document
Try { [System.Xml.XmlDocument] $XMLDocument = new-object System.Xml.XmlDocument }
Catch [Exception] {
Write-Verbose ("Failed to create a System.Xml.XmlDocument" + $Error[0][0])
return -3
}
Write-Verbose ("Have an XMLDocument to load")
# Load up the XML document from the XML
Try { $XMLDocument.LoadXML($XML) }
Catch [Exception] {
Write-Verbose ("Failed to create load XMLDocument using " + $XML + $Error[0][0])
return -3
}
Write-Verbose ("XML was loaded")
# Extract all the tags
Try {
[String] $XMLLatest = GetTag $XMLDocument "Latest"
[String] $XMLDate = GetTag $XMLDocument "Date"
[String] $XMLURL = GetTag $XMLDocument "URL"
[String] $XMLType = GetTag $XMLDocument "Type"
[String] $XMLAbout = GetTag $XMLDocument "About"
} Catch [Exception] {
Write-Verbose ("Failed to GetTag " + $XML + $Error[0][0])
return -3
}
Write-Verbose ("Latest " + $XMLLatest)
Write-Verbose ("Date " + $XMLDate)
Write-Verbose ("URL " + $XMLURL)
Write-Verbose ("Type " + $XMLType)
Write-Verbose ("About " + $XMLAbout)
if ([System.Double]$XMLLatest -gt [System.Double]$script:version) {
$Latest = "Version " + $XMLLatest + " (" + $XMLDate + ") is available from " + $XMLURL + ". "
if ($XMLType.Length) {$Latest = $Latest + "`n" + ($XMLType) + ". "}
if ($XMLAbout.Length) {$Latest = $Latest + "`n" + ($XMLAbout)}
Write-Warning $Latest
$script:WarningCount = $script:WarningCount + 1
return -1
} else {
if ([System.Double]$XMLLatest -eq [System.Double]$script:version) {
Write-Verbose "Are running latest version"
return 0
} else {
Write-Verbose "***Probably developing. Running $script:version Latest is $XMLLatest"
return -2
}
}
} catch [Exception] { # Clone catch
Write-Host -ForegroundColor Red "ERROR: Exception in Check-LatestVersion()"
Write-Host -ForegroundColor Red $_.Exception.ToString()
return -3
}
}
# ---------------------------------------------------------------------------------------------------------------------------
# Function to perform simple preflight migration checks.
# ---------------------------------------------------------------------------------------------------------------------------
Function PreFlight-Checks {
Try {
Write-Verbose ">> PreFlight_Checks"
$script:ProgressPoint = 200
# Check for elevation
$GetCurrent = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
if (!$GetCurrent.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) { Cleanup "This script must be run elevated." }
#Check the PSVersion
$script:ProgressPoint = 201
if ($global:PSVersionTable.PSVersion.Major -ne 5 -and !$NoPSVersionCheck) {
$script:ProgressPoint = 202
Write-Warning "This script is designed for PowerShell v5.0. Behaviour on other versions is untested."
Write-Warning "To override version check, specify parameter -NoPSVersionCheck."
$script:WarningCount = $script:WarningCount + 1
Cleanup
}
# Find the virtual machine. We don't need this for apply IFF the user has supplied both a VHDX size for the target (as we're not
# using the source boot VHD for sizing) and the name of the output VHDX.
$script:ProgressPoint = 203
if (($Action -ne "Apply") -or `
(($Action -eq "Apply") -and ($VHDXSizeGB -ne 0) -and ($VHDX -eq "")) -or `
(($Action -eq "Apply") -and ($VHDXSizeGB -eq 0)) ) {
$script:ProgressPoint = 204
Write-Info "Locating virtual machine '$VMNAME'..."
$script:SourceVMObject = Get-VM -EA SilentlyContinue -Name $VMNAME
if (!$script:SourceVMObject){
$script:ProgressPoint = 217
Write-Verbose "Cleanup due to VM was not found"
Cleanup "Virtual Machine '$VMNAME' could not be found."
}
Write-Verbose "Found VM by name"
# Make sure only one VM
$script:ProgressPoint = 205
if ($script:SourceVMObject -is [Array]) {
$script:ProgressPoint = 206
Write-Verbose "Cleanup due to multiple VMs"
Cleanup "Multiple VMs with the name '$VMNAME' were found."
}
Write-Verbose "And there is a single VM of that name"
# VM must be off
$script:ProgressPoint = 207
Write-Info "Validating virtual machine configuration..."
if ($script:SourceVMObject.State -ne 'Off') {
$script:ProgressPoint = 208
Write-Verbose ("Cleanup due to "+ $script:SourceVMObject.State)
Cleanup ("'" + $VMName + "' must be off for conversion to continue.")
}
Write-Verbose "VM is off"
# VM must not have any checkpoints (snapshots). Not going to distinguish at this point recovery/replica etc
$script:ProgressPoint = 209
$Checkpoints = Get-VMSnapshot -VM $script:SourceVMObject -EA SilentlyContinue -SnapshotType Standard
if ($Checkpoints) {
$script:ProgressPoint = 210
Write-Verbose "Cleanup due to checkpoints found"
Cleanup "Checkpoints are not supported for the conversion process."
}
Write-Verbose "No checkpoints were found"
# Must be a Generation 1 VM
$script:ProgressPoint = 211
if ($script:SourceVMObject.Generation -ne 1) {
$script:ProgressPoint = 212
Write-Verbose "Cleanup due to not a generation 1 virtual machine"
Cleanup ("'" + $VMName + "'Must be a Generation 1 VM!")
}
# Must not have replica enabled. This may work fine, but not tested or verified.
$script:ProgressPoint = 213
if ($script:SourceVMObject.ReplicationState -ne "Disabled") {
$script:ProgressPoint = 214
Write-Verbose "Replica is enabled"
if ($IgnoreReplicaCheck = $True) {
Write-Warning ("This script has not been validated for VMs with replica enabled. Using the override check is experimental only. Remember that *IF* the VM is successfully converted, you will need to re-enable replica once complete.")
$script:WarningCount = $script:WarningCount + 1
} else {
$script:ProgressPoint = 215
CleanUp "Cleanup due to replication being enabled. Use the -IgnoreReplicaCheck to override. This has not been validated to operate correctly. If it works, the new generation 2 virtual machine will not have replica enabled."
}
}
}
# Make sure the target does not exist (unless user says it's fine to overwrite it). Not applicable for capture and apply
$script:ProgressPoint = 216
if (($Action -ne "Capture") -and ($Action -ne "Apply")) {
if ($NewVMName -eq "") {
$script:ProgressPoint = 220
$script:NewVMName = ($script:SourceVMObject).VMName + " (Generation 2)"
Write-Verbose ("Settting New VMName to " + $NewVMName)
}
$script:ProgressPoint = 230
$TestTargetVM = Get-VM -EA SilentlyContinue -Name $NewVMName
if ($TestTargetVM) {
Write-Verbose "Target VM exists"
$script:ProgressPoint = 240
if ($OverwriteVM) {
$script:ProgressPoint = 250
Write-Verbose ("Removing VM " + $NewVMName)
Remove-VM $TestTargetVM -ErrorAction SilentlyContinue -Force
if (!$?) { Cleanup ("Failed to remove "+ $NewVMName + "`n"+ $Error[0][0]) }
} else {
$script:ProgressPoint = 260
CleanUp ($NewVMName + " exists. Use -OverwriteVM to force deletion")
}
}
$script:ProgressPoint = 270
}
$script:ProgressPoint = 280
}
Catch [Exception] {
$script:ProgressPoint += 90000
Write-Host -ForegroundColor Red ("Exception in PreFlight-Checks: " + $_.Exception.ToString())
Cleanup ("Exception in PreFlight-Checks")
}
Finally {
Write-Verbose "<< PreFlight-Checks()"
}
} # PreFlight_Checks()
# ---------------------------------------------------------------------------------------------------------------------------
# Function to locate the boot disk on the source VM, check it is not shared and mount it.
# ---------------------------------------------------------------------------------------------------------------------------
Function Locate-SourceBootDisk ($VM, [Ref] $SourceBootDiskPath) {
try {
$script:ProgressPoint = 300
Write-Verbose ">> Locate-SourceBootDisk"
$SourceBootDiskPath.Value = ""
# The boot disk is assumed to be the first disk found on IDE in order. This is far from
# perfect, but is good for the majority case.
$i = 0
do {
$script:ProgressPoint = 301
Write-Verbose ("Examining "+([math]::floor([int] $i / [int] 2)) + ":" +($i%2) )
$Disk = (Get-VMHardDiskDrive $VM `
-ControllerType IDE `
-ControllerNumber ([math]::floor([int] $i / [int] 2)) `
-ControllerLocation ($i%2) -ErrorAction SilentlyContinue)
$script:ProgressPoint = 302
if (!$?) { Cleanup ("Failed to Get-VMHardDiskDrive`n"+ $Error[0][0]) }
$i++
if ($Disk -ne $Null) { Write-Verbose ($Disk.Path) }
$script:ProgressPoint = 303
} while (($i -le 3) -and (!$Disk))
$script:ProgressPoint = 310
if (!($Disk)){ Cleanup "No boot disk was found for this VM." }
# Give up if likely to be running a guest cluster.
$script:ProgressPoint = 320
if ($Disk.SupportPersistentReservations) {
$script:ProgressPoint = 321
Write-Warning (($Disk.Path) + " is shared.")
$script:WarningCount = $script:WarningCount + 1
}
# ByRef output parameter
$script:ProgressPoint = 330
$SourceBootDiskPath.Value = $Disk.Path
Write-Info ("Identified boot disk is '" + $Disk.Path + "'")
Write-Verbose "<< Locate-SourceBootDisk"
$script:ProgressPoint = 397
}
Catch [Exception] {
$script:ProgressPoint +=90000
Write-Host -ForegroundColor Red ("Exception in Locate-SourceBootDisk: " + $_.Exception.ToString())
Cleanup ("Exception in Locate-SourceBootDisk")
}
Finally {
Write-Verbose "<< Validate-Parameters()"
}
} # End Locate-SourceBootDisk
# ---------------------------------------------------------------------------------------------------------------------------
# Function to locate the boot disk on the source VM, check it is not shared and mount it.
# ---------------------------------------------------------------------------------------------------------------------------
Function Mount-Disk ($Path, [Ref] $Mounted) {
try {
$script:ProgressPoint = 400
Write-Verbose ">> Mount-Disk"
$Mounted.Value = $False
Write-Verbose ("Mounting " + $Path + "...")
Mount-DiskImage $Path -EA SilentlyContinue
if (!$?) { Cleanup ("Mount operation failed`n"+ $Error[0][0]) }
Write-Verbose "The disk was mounted"
($Mounted.Value) = $True
$script:ProgressPoint = 497
}
Catch [Exception] {
$script:ProgressPoint += 90000
Write-Host -ForegroundColor Red ("Exception in Mount-Disk: " + $_.Exception.ToString())
Cleanup ("Exception in Mount-Disk")
}
Finally {
Write-Verbose "<< Mount-Disk()"
}
} # End Mount-Disk
# ---------------------------------------------------------------------------------------------------------------------------
# Function to allocate two free drive letters.
# ---------------------------------------------------------------------------------------------------------------------------
Function Allocate-TwoFreeDriveLetters ([Ref] $First, [Ref] $Second) {
try {
$script:ProgressPoint = 500
# Get some target drive letters which are not assigned.
Write-Verbose ">> Allocate-TwoFreeDriveLetters"
if (($First.Value -ne "") -and ($Second.Value -ne "")) {
$script:ProgressPoint = 501
Write-Verbose ("Test hook for free drive letters " + $First.Value + " " + $Second.Value )
} else {
$First.Value = ""
$Second.Value = ""
$TempArray = ls function:[d-z]: -n | ?{ !(test-path $_) } | select -last 2
Write-Verbose "Using temporary drive letters $($TempArray -join " ")"
if (1 -ne $TempArray.GetUpperBound(0)) {
$script:ProgressPoint = 502
CleanUp "Not enough free drive letters could be located to proceed."
}
$First.Value = $TempArray[0]
$Second.Value = $TempArray[1]
}
$script:ProgressPoint = 597
}
Catch [Exception] {
$script:ProgressPoint += 90000
Write-Host -ForegroundColor Red ("Exception in Allocate-TwoFreeDriveLetters: " + $_.Exception.ToString())
Cleanup ("Exception in Allocate-TwoFreeDriveLetters")
}
Finally {
Write-Verbose "<< Allocate-TwoFreeDriveLetters"
}
}
# ---------------------------------------------------------------------------------------------------------------------------
# Function to validate the source boot disk contains a version of Windows we can migrate
# ---------------------------------------------------------------------------------------------------------------------------
Function Validate-SourceWindowsInstallation ( [String] $BootDiskFileName, `
[Ref] $ByRefPartition, `
[Ref] $ByRefPartitionNum, `
[Ref] $ByRefUsed ) {
# Taking a simple approach rather than opening the BCD store on the source active partition as in the original prototype.
# Look at each drive letter which has been mapped from the source attempting to locate a Windows installation.
# If more than one is found (eg multi-boot) then error out. If none are found, we have a problem.
# When one and only one is found, that's the source partition
try {
$script:ProgressPoint = 600
Write-Verbose ">> Validate-SourceWindowsInstallation"
$ByRefPartition.Value = $Null
$ByRefPartitionNum.Value = -1
$ByRefUsed.Value = 0
$WorkingPartition = $Null
# Get the partition drive letters
$SourcePartitions = ( (Get-DiskImage($BootDiskFileName)) | get-disk | get-partition)
$script:ProgressPoint = 601
$NumberFound = 0
$DriveLettersAssigned = 0
$DriveLetters = ""
$NumberOfWindowsCopiesFound = 0
# GPT is pretty unexpected! Worth testing though just in case
if ("GPT" -eq (Get-DiskImage($BootDiskFileName) | Get-Disk ).PartitionStyle) {
$script:ProgressPoint = 602
CleanUp ("$BootDiskFileName is GPT which cannot be a valid boot disk for a generation 1 virtual machine!")
}
$script:ProgressPoint = 603
# Find out what we're working with
$SourcePartitions | ForEach-Object {
$script:ProgressPoint = 604
$_ | fl * | Out-String | Write-Verbose
$NumberFound ++
Write-Verbose ("Found Partition "+$_.PartitionNumber+", type "+$_.Type+", size "+$_.Size+" at offset "+$_.Offset+" on disk "+ $_.DiskNumber+" drive letter "+$_.DriveLetter)
if ($_.DriveLetter -match "^[a-zA-Z]") { # Weird. Only way I could find out whether drive letter assigned
$script:ProgressPoint = 605
$DriveLettersAssigned++
$DriveLetters = $DriveLetters + $_.DriveLetter[0] + " "
} else {
$script:ProgressPoint = 606
# Not when action is apply
if ($Action -ne "Apply") {
Write-Warning ("Partition "+$_.PartitionNumber+", type "+$_.Type+", size "+$_.Size+" at offset "+$_.Offset+" on disk "+ $_.DiskNumber+" (" + $BootDiskFileName + ") does not have a drive letter and will be ignored")
$script:WarningCount++
}
}
}
$script:ProgressPoint = 620
Write-Verbose ("Partition count "+$NumberFound)
Write-Verbose ("Drive Letters "+$DriveLettersAssigned + " " +$DriveLetters)
# We must have at least one partition
if ($NumberFound -eq 0) { CleanUp "No partitions were located on the source disk" }
# And we must have at least one partition with a drive letter
if ($DriveLettersAssigned -eq 0) { Cleanup "No partitions on the source disk were assigned drive letters when it was mounted" }
$script:ProgressPoint = 630
if ($DriveLettersAssigned -gt 1) {
Write-Info ("Source drive letters are " + $DriveLetters)
} else {
Write-Info ("Source drive letter is " + $DriveLetters)
}
# Loop again through them looking for partitions containing Windows (over simplified check)
$SourcePartitions | ForEach-Object {
$script:ProgressPoint = 631
if ($_.DriveLetter -match "^[a-zA-Z]") {
$script:ProgressPoint = 632
# Check for ntdll.dll
if ($True -eq (Test-Path (($_.DriveLetter) + ":\windows\system32\ntdll.dll"))) {
$script:ProgressPoint = 633
Write-Verbose "Found a Windows Installation"
$NumberOfWindowsCopiesFound++