-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03-Convert-Gen1toGen2.ps1
More file actions
480 lines (407 loc) · 19 KB
/
03-Convert-Gen1toGen2.ps1
File metadata and controls
480 lines (407 loc) · 19 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
#Requires -RunAsAdministrator
#Requires -Modules Hyper-V, FailoverClusters
<#
.SYNOPSIS
Converts a Gen 1 VM to Gen 2 on a Hyper-V failover cluster.
.DESCRIPTION
This script runs on a Hyper-V cluster node and:
1. Exports the Gen 1 VM configuration (NICs, memory, CPU, disks, etc.)
2. Backs up the VHDX files
3. Removes the Gen 1 VM from the cluster and Hyper-V (preserving VHDXs)
4. Creates a new Gen 2 VM with the same configuration
5. Attaches the existing VHDX disks (already converted to GPT via Script 02)
6. Adds the VM back to the failover cluster
7. Starts the VM and validates the boot
No Azure connectivity, Arc registration, or Azure resource management is performed.
This script is for the Hyper-V path only. If you need the VM managed in the Azure
portal, use the Azure Local path (scripts/azurelocal/).
PREREQUISITES:
- Script 01 has been run (environment setup, config exports exist)
- Script 02 has been run inside the guest (MBR → GPT conversion done)
- The VM is SHUT DOWN
.PARAMETER VMName
Name of the VM to convert.
.PARAMETER WorkingDirectory
Path to the conversion working directory (created by Script 01).
.PARAMETER BackupVHDX
Create a backup copy of VHDX files before conversion. Default: $true
.EXAMPLE
.\03-Convert-Gen1toGen2.ps1 `
-VMName "WebServer01" `
-WorkingDirectory "C:\ClusterStorage\Volume01\Gen2Conversion"
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true)]
[string]$VMName,
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory,
[Parameter()]
[bool]$BackupVHDX = $true
)
# ── Global Settings ──────────────────────────────────────────────────────────
$ErrorActionPreference = 'Stop'
$LogFile = Join-Path $WorkingDirectory "Logs\Gen2Convert_${VMName}_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$entry = "[$timestamp] [$Level] $Message"
Write-Host $entry -ForegroundColor $(switch ($Level) { "ERROR" { "Red" } "WARN" { "Yellow" } "SUCCESS" { "Green" } default { "Cyan" } })
Add-Content -Path $LogFile -Value $entry
}
Write-Log "═══════════════════════════════════════════════════════════════"
Write-Log " Hyper-V Gen 1 → Gen 2 VM Conversion"
Write-Log " VM: $VMName"
Write-Log "═══════════════════════════════════════════════════════════════"
# ── Step 1: Load and Validate VM Configuration ──────────────────────────────
Write-Log "Step 1: Loading VM configuration..."
# Check for config file from Script 01
$configPath = Join-Path $WorkingDirectory "Configs\${VMName}_config.json"
$savedConfig = $null
if (Test-Path $configPath) {
$savedConfig = Get-Content $configPath -Raw | ConvertFrom-Json
Write-Log " Loaded saved config from: $configPath" -Level "SUCCESS"
}
# Get live VM state
$vm = Get-VM -Name $VMName -ErrorAction Stop
Write-Log " VM State: $($vm.State)"
Write-Log " Generation: $($vm.Generation)"
Write-Log " Host: $($vm.ComputerName)"
if ($vm.Generation -ne 1) {
Write-Log "VM '$VMName' is already Generation $($vm.Generation). Nothing to do." -Level "WARN"
exit 0
}
if ($vm.State -ne 'Off') {
Write-Log "VM must be in 'Off' state. Current state: $($vm.State)" -Level "ERROR"
Write-Log " Please shut down the VM first (after running Script 02 inside the guest)." -Level "ERROR"
throw "VM is not shut down."
}
# Check for checkpoints
$checkpoints = Get-VMCheckpoint -VM $vm
if ($checkpoints.Count -gt 0) {
Write-Log "VM has $($checkpoints.Count) checkpoint(s). These MUST be removed before conversion." -Level "ERROR"
$checkpoints | ForEach-Object { Write-Log " - $($_.Name) (Created: $($_.CreationTime))" -Level "ERROR" }
throw "Remove all checkpoints before proceeding."
}
# ── Step 2: Capture Full VM Configuration ────────────────────────────────────
Write-Log ""
Write-Log "Step 2: Capturing VM configuration..."
# Processor
$processorCount = $vm.ProcessorCount
Write-Log " Processors: $processorCount"
# Memory
$memoryStartup = $vm.MemoryStartup
$memoryMin = $vm.MemoryMinimum
$memoryMax = $vm.MemoryMaximum
$dynamicMemory = $vm.DynamicMemoryEnabled
Write-Log " Memory Startup: $($memoryStartup / 1MB) MB"
Write-Log " Dynamic Memory: $dynamicMemory"
if ($dynamicMemory) {
Write-Log " Memory Min: $($memoryMin / 1MB) MB | Max: $($memoryMax / 1MB) MB"
}
# Hard disks
$hardDisks = Get-VMHardDiskDrive -VM $vm
$diskDetails = @()
foreach ($disk in $hardDisks) {
$vhd = Get-VHD -Path $disk.Path -ErrorAction SilentlyContinue
$detail = [PSCustomObject]@{
Path = $disk.Path
ControllerType = $disk.ControllerType.ToString()
ControllerNumber = $disk.ControllerNumber
ControllerLocation = $disk.ControllerLocation
VhdFormat = if ($vhd) { $vhd.VhdFormat.ToString() } else { "Unknown" }
SizeGB = if ($vhd) { [math]::Round($vhd.Size / 1GB, 2) } else { 0 }
}
$diskDetails += $detail
Write-Log " Disk: $($disk.Path) | $($detail.ControllerType) $($detail.ControllerNumber):$($detail.ControllerLocation) | $($detail.VhdFormat) | $($detail.SizeGB) GB"
}
# Identify boot disk (first IDE disk is typically boot on Gen 1)
$bootDiskPath = ($hardDisks | Where-Object { $_.ControllerType -eq "IDE" -and $_.ControllerNumber -eq 0 -and $_.ControllerLocation -eq 0 }).Path
if (-not $bootDiskPath) {
$bootDiskPath = $hardDisks[0].Path
Write-Log " Could not identify boot disk by IDE 0:0, using first disk: $bootDiskPath" -Level "WARN"
}
Write-Log " Boot Disk: $bootDiskPath"
# Network adapters
$nics = Get-VMNetworkAdapter -VM $vm
$nicDetails = @()
foreach ($nic in $nics) {
$vlan = Get-VMNetworkAdapterVlan -VMNetworkAdapter $nic -ErrorAction SilentlyContinue
$detail = [PSCustomObject]@{
Name = $nic.Name
SwitchName = $nic.SwitchName
MacAddress = $nic.MacAddress
VlanId = if ($vlan) { $vlan.AccessVlanId } else { 0 }
IsLegacy = $nic.IsLegacy
}
$nicDetails += $detail
Write-Log " NIC: $($nic.Name) | Switch: $($nic.SwitchName) | MAC: $($nic.MacAddress) | VLAN: $($detail.VlanId) | Legacy: $($nic.IsLegacy)"
}
# Auto start/stop actions
$autoStart = $vm.AutomaticStartAction
$autoStop = $vm.AutomaticStopAction
$autoStartDelay = $vm.AutomaticStartDelay
Write-Log " Auto Start: $autoStart (Delay: ${autoStartDelay}s) | Auto Stop: $autoStop"
# VM notes
$vmNotes = $vm.Notes
# Get cluster resource info
$clusterGroup = $null
try {
$clusterGroup = Get-ClusterGroup -Name $VMName -ErrorAction SilentlyContinue
if ($clusterGroup) {
Write-Log " Cluster Group: $($clusterGroup.Name) | State: $($clusterGroup.State) | Owner: $($clusterGroup.OwnerNode)" -Level "SUCCESS"
}
}
catch {
Write-Log " VM is not in a cluster group (standalone)" -Level "WARN"
}
# ── Step 3: VHD Format Check and Backup ─────────────────────────────────────
Write-Log ""
Write-Log "Step 3: VHD format validation and backup..."
foreach ($disk in $diskDetails) {
if ($disk.VhdFormat -eq "VHD") {
Write-Log " CONVERTING VHD → VHDX: $($disk.Path)" -Level "WARN"
$newPath = [System.IO.Path]::ChangeExtension($disk.Path, ".vhdx")
if (-not $PSCmdlet.ShouldProcess($disk.Path, "Convert VHD to VHDX")) {
throw "User cancelled VHD conversion."
}
Convert-VHD -Path $disk.Path -DestinationPath $newPath -VHDType Dynamic
Write-Log " Converted: $newPath" -Level "SUCCESS"
if ($disk.Path -eq $bootDiskPath) { $bootDiskPath = $newPath }
$disk.Path = $newPath
}
}
if ($BackupVHDX) {
$backupDir = Join-Path $WorkingDirectory "Backups\$VMName"
if (-not (Test-Path $backupDir)) { New-Item -Path $backupDir -ItemType Directory -Force | Out-Null }
foreach ($disk in $diskDetails) {
$destPath = Join-Path $backupDir (Split-Path $disk.Path -Leaf)
Write-Log " Backing up: $($disk.Path) → $destPath"
Write-Log " This may take a while for large disks..."
Copy-Item -Path $disk.Path -Destination $destPath -Force
Write-Log " Backup complete: $([math]::Round((Get-Item $destPath).Length / 1GB, 2)) GB" -Level "SUCCESS"
}
}
# ── Step 4: Remove Gen 1 VM (Preserve Disks) ────────────────────────────────
Write-Log ""
Write-Log "Step 4: Removing Gen 1 VM..."
if (-not $PSCmdlet.ShouldProcess($VMName, "Remove Gen 1 VM (disks will be preserved)")) {
throw "User cancelled VM removal."
}
# Remove from cluster first if clustered
if ($clusterGroup) {
Write-Log " Removing from failover cluster..."
try {
Remove-ClusterGroup -Name $VMName -RemoveResources -Force
Write-Log " Removed from cluster" -Level "SUCCESS"
}
catch {
Write-Log " Cluster removal issue: $_ (continuing...)" -Level "WARN"
}
Start-Sleep -Seconds 3
}
# Remove VM (without deleting VHDXs)
Write-Log " Removing Hyper-V VM '$VMName' (preserving VHDXs)..."
Remove-VM -Name $VMName -Force
Write-Log " Gen 1 VM removed" -Level "SUCCESS"
Start-Sleep -Seconds 3
# ── Step 5: Create Gen 2 VM ─────────────────────────────────────────────────
Write-Log ""
Write-Log "Step 5: Creating Gen 2 VM..."
$vmPath = Split-Path (Split-Path $bootDiskPath -Parent) -Parent
$newVMParams = @{
Name = $VMName
Generation = 2
MemoryStartupBytes = $memoryStartup
VHDPath = $bootDiskPath
Path = $vmPath
SwitchName = $nicDetails[0].SwitchName
}
Write-Log " Creating VM with params:"
$newVMParams.GetEnumerator() | ForEach-Object { Write-Log " $($_.Key): $($_.Value)" }
$newVM = New-VM @newVMParams
Write-Log " Gen 2 VM created" -Level "SUCCESS"
# ── Step 6: Configure VM Settings ───────────────────────────────────────────
Write-Log ""
Write-Log "Step 6: Applying VM configuration..."
# Processor
Set-VMProcessor -VM $newVM -Count $processorCount
Write-Log " Processors: $processorCount"
# Memory
if ($dynamicMemory) {
Set-VMMemory -VM $newVM -DynamicMemoryEnabled $true -MinimumBytes $memoryMin -MaximumBytes $memoryMax -StartupBytes $memoryStartup
Write-Log " Dynamic Memory: $($memoryMin / 1MB)MB - $($memoryMax / 1MB)MB (Start: $($memoryStartup / 1MB)MB)"
}
# Secure Boot
try {
Set-VMFirmware -VM $newVM -EnableSecureBoot On -SecureBootTemplate "MicrosoftWindows"
Write-Log " Secure Boot: Enabled (MicrosoftWindows template)"
}
catch {
Write-Log " Secure Boot configuration issue: $_" -Level "WARN"
try {
Set-VMFirmware -VM $newVM -EnableSecureBoot Off
Write-Log " Secure Boot: Disabled (fallback)" -Level "WARN"
}
catch {
Write-Log " Could not configure Secure Boot: $_" -Level "WARN"
}
}
# Attach additional data disks
$additionalDisks = $diskDetails | Where-Object { $_.Path -ne $bootDiskPath }
$scsiLocation = 1
foreach ($disk in $additionalDisks) {
Write-Log " Attaching data disk: $($disk.Path) at SCSI 0:$scsiLocation"
Add-VMHardDiskDrive -VM $newVM -ControllerType SCSI -ControllerNumber 0 -ControllerLocation $scsiLocation -Path $disk.Path
$scsiLocation++
}
# Configure NICs
$firstNic = Get-VMNetworkAdapter -VM $newVM | Select-Object -First 1
if ($nicDetails[0].VlanId -and $nicDetails[0].VlanId -gt 0) {
Set-VMNetworkAdapterVlan -VMNetworkAdapter $firstNic -Access -VlanId $nicDetails[0].VlanId
Write-Log " NIC 1 VLAN: $($nicDetails[0].VlanId)"
}
if ($nicDetails[0].MacAddress -and $nicDetails[0].MacAddress -ne "000000000000") {
try {
Set-VMNetworkAdapter -VMNetworkAdapter $firstNic -StaticMacAddress $nicDetails[0].MacAddress
Write-Log " NIC 1 MAC (static): $($nicDetails[0].MacAddress)"
}
catch {
Write-Log " Could not set static MAC (may be in use): $_" -Level "WARN"
}
}
for ($i = 1; $i -lt $nicDetails.Count; $i++) {
$nic = $nicDetails[$i]
if ($nic.IsLegacy) {
Write-Log " Skipping legacy NIC '$($nic.Name)' — not supported on Gen 2" -Level "WARN"
continue
}
Write-Log " Adding NIC: $($nic.Name) on switch $($nic.SwitchName)"
$newNic = Add-VMNetworkAdapter -VM $newVM -Name $nic.Name -SwitchName $nic.SwitchName -PassThru
if ($nic.VlanId -and $nic.VlanId -gt 0) {
Set-VMNetworkAdapterVlan -VMNetworkAdapter $newNic -Access -VlanId $nic.VlanId
}
if ($nic.MacAddress -and $nic.MacAddress -ne "000000000000") {
try {
Set-VMNetworkAdapter -VMNetworkAdapter $newNic -StaticMacAddress $nic.MacAddress
}
catch {
Write-Log " Could not set static MAC for $($nic.Name): $_" -Level "WARN"
}
}
}
# Auto start/stop actions
Set-VM -VM $newVM -AutomaticStartAction $autoStart -AutomaticStopAction $autoStop -AutomaticStartDelay $autoStartDelay
Write-Log " Auto Start: $autoStart | Auto Stop: $autoStop"
# Notes
$conversionNote = "[Converted Gen1→Gen2 on $(Get-Date -Format 'yyyy-MM-dd HH:mm')]"
Set-VM -VM $newVM -Notes $(if ($vmNotes) { "$vmNotes`n$conversionNote" } else { $conversionNote })
# Enable TPM
try {
$keyProtector = New-HgsGuardian -Name "UntrustedGuardian_$VMName" -GenerateCertificates -ErrorAction SilentlyContinue
if ($keyProtector) {
$kp = New-HgsKeyProtector -Owner $keyProtector -AllowUntrustedRoot
Set-VMKeyProtector -VM $newVM -KeyProtector $kp.RawData
Enable-VMTPM -VM $newVM
Write-Log " TPM: Enabled" -Level "SUCCESS"
}
}
catch {
Write-Log " TPM: Could not enable (non-critical): $_" -Level "WARN"
}
Write-Log " VM configuration applied" -Level "SUCCESS"
# ── Step 7: Add to Failover Cluster ─────────────────────────────────────────
Write-Log ""
Write-Log "Step 7: Adding VM to failover cluster..."
try {
Add-ClusterVirtualMachineRole -VMName $VMName
Write-Log " VM added to cluster" -Level "SUCCESS"
}
catch {
Write-Log " Could not add to cluster: $_" -Level "WARN"
Write-Log " You may need to add manually: Add-ClusterVirtualMachineRole -VMName '$VMName'" -Level "WARN"
}
# ── Step 8: Start VM and Validate Boot ──────────────────────────────────────
Write-Log ""
Write-Log "Step 8: Starting Gen 2 VM..."
try {
Start-VM -Name $VMName
Write-Log " VM starting..." -Level "SUCCESS"
Write-Log " Waiting for VM to reach heartbeat (up to 5 minutes)..."
$timeout = 300
$elapsed = 0
$heartbeat = $false
while ($elapsed -lt $timeout) {
Start-Sleep -Seconds 10
$elapsed += 10
$vmState = Get-VM -Name $VMName
if ($vmState.Heartbeat -match "Ok") {
$heartbeat = $true
break
}
Write-Log " Waiting... ($elapsed seconds) State: $($vmState.State) Heartbeat: $($vmState.Heartbeat)"
}
if ($heartbeat) {
Write-Log " VM booted successfully with heartbeat!" -Level "SUCCESS"
}
else {
Write-Log " VM did not reach heartbeat within timeout." -Level "WARN"
Write-Log " Check the VM console — may need Secure Boot disabled or boot order adjusted." -Level "WARN"
Write-Log " Troubleshooting:" -Level "WARN"
Write-Log " 1. Stop-VM -Name '$VMName' -Force" -Level "WARN"
Write-Log " 2. Set-VMFirmware -VMName '$VMName' -EnableSecureBoot Off" -Level "WARN"
Write-Log " 3. Start-VM -Name '$VMName'" -Level "WARN"
}
}
catch {
Write-Log " Failed to start VM: $_" -Level "ERROR"
}
# ── Step 9: Final Validation ─────────────────────────────────────────────────
Write-Log ""
Write-Log "Step 9: Final validation..."
$finalVM = Get-VM -Name $VMName
Write-Log " VM Name: $($finalVM.Name)"
Write-Log " Generation: $($finalVM.Generation)"
Write-Log " State: $($finalVM.State)"
Write-Log " Heartbeat: $($finalVM.Heartbeat)"
Write-Log " Processors: $($finalVM.ProcessorCount)"
Write-Log " Memory: $($finalVM.MemoryAssigned / 1MB) MB"
$finalDisks = Get-VMHardDiskDrive -VM $finalVM
foreach ($disk in $finalDisks) {
Write-Log " Disk: $($disk.Path) ($($disk.ControllerType) $($disk.ControllerNumber):$($disk.ControllerLocation))"
}
$finalNics = Get-VMNetworkAdapter -VM $finalVM
foreach ($nic in $finalNics) {
Write-Log " NIC: $($nic.Name) → $($nic.SwitchName) (MAC: $($nic.MacAddress))"
}
try {
$clusterStatus = Get-ClusterGroup -Name $VMName -ErrorAction SilentlyContinue
if ($clusterStatus) {
Write-Log " Cluster: $($clusterStatus.State) on $($clusterStatus.OwnerNode)" -Level "SUCCESS"
}
}
catch {
Write-Log " Cluster: Not detected" -Level "WARN"
}
# ── Summary ──────────────────────────────────────────────────────────────────
Write-Log ""
Write-Log "═══════════════════════════════════════════════════════════════"
Write-Log " CONVERSION COMPLETE"
Write-Log "═══════════════════════════════════════════════════════════════"
Write-Log " VM '$VMName' converted from Gen 1 → Gen 2"
Write-Log " Generation: $($finalVM.Generation)"
Write-Log " State: $($finalVM.State)"
Write-Log " Log: $LogFile"
if ($BackupVHDX) {
Write-Log ""
Write-Log " VHDX backups are at: $(Join-Path $WorkingDirectory "Backups\$VMName")"
Write-Log " Remove backups once you have confirmed everything is working."
}
Write-Log ""
Write-Log " POST-CONVERSION CHECKLIST:"
Write-Log " [ ] Verify VM boots and OS is functional"
Write-Log " [ ] Confirm BIOS Mode shows 'UEFI' (msinfo32 inside guest)"
Write-Log " [ ] Verify disk shows as GPT in guest Disk Management"
Write-Log " [ ] Test application functionality"
Write-Log " [ ] Remove VHDX backups when satisfied"
Write-Log "═══════════════════════════════════════════════════════════════"