-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04-Batch-ConvertVMs.ps1
More file actions
274 lines (226 loc) · 11.2 KB
/
04-Batch-ConvertVMs.ps1
File metadata and controls
274 lines (226 loc) · 11.2 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
#Requires -RunAsAdministrator
<#
.SYNOPSIS
Batch orchestrator for converting multiple Gen 1 VMs to Gen 2 on a Hyper-V failover cluster.
.DESCRIPTION
This script orchestrates the conversion of multiple VMs by:
- Reading the VM inventory CSV from Script 01
- Allowing selection of VMs to convert
- Invoking Script 03 for each VM sequentially
- Tracking progress and generating a summary report
No Azure connectivity, Arc registration, or Azure resource management is performed.
This script is for the Hyper-V path only. If you need the VMs managed in the Azure
portal, use the Azure Local path (scripts/azurelocal/).
IMPORTANT: Script 02 (MBR→GPT) must be run inside EACH guest VM manually
before this batch script can process them.
.PARAMETER WorkingDirectory
Path to the conversion working directory (created by Script 01).
.PARAMETER VMNames
Optional array of specific VM names to convert. If omitted, shows all Gen 1 VMs for selection.
.EXAMPLE
# Interactive — shows all Gen 1 VMs for selection
.\04-Batch-ConvertVMs.ps1 `
-WorkingDirectory "C:\ClusterStorage\Volume01\Gen2Conversion"
# Specific VMs
.\04-Batch-ConvertVMs.ps1 `
-WorkingDirectory "C:\ClusterStorage\Volume01\Gen2Conversion" `
-VMNames @("WebServer01", "SQLServer01", "AppServer01")
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$WorkingDirectory,
[Parameter()]
[string[]]$VMNames
)
$ErrorActionPreference = 'Stop'
$BatchLogFile = Join-Path $WorkingDirectory "Logs\BatchConversion_$(Get-Date -Format 'yyyyMMdd_HHmmss').log"
$ScriptRoot = $PSScriptRoot
if (-not $ScriptRoot) { $ScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path }
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 $BatchLogFile -Value $entry
}
Write-Log "═══════════════════════════════════════════════════════════════"
Write-Log " Hyper-V Batch Gen1 → Gen2 Conversion"
Write-Log "═══════════════════════════════════════════════════════════════"
# ── Load Inventory ───────────────────────────────────────────────────────────
$inventoryFiles = Get-ChildItem -Path (Join-Path $WorkingDirectory "Configs") -Filter "Gen1_VM_Inventory_*.csv" |
Sort-Object LastWriteTime -Descending
if ($inventoryFiles.Count -eq 0) {
Write-Log "No inventory CSV found. Run Script 01 first!" -Level "ERROR"
throw "Missing inventory file."
}
$inventory = Import-Csv -Path $inventoryFiles[0].FullName
Write-Log "Loaded inventory: $($inventoryFiles[0].Name) ($($inventory.Count) VMs)"
# ── Filter VMs ───────────────────────────────────────────────────────────────
if ($VMNames) {
$selectedVMs = $inventory | Where-Object { $_.VMName -in $VMNames }
$missing = $VMNames | Where-Object { $_ -notin $inventory.VMName }
if ($missing) {
Write-Log "VMs not found in inventory: $($missing -join ', ')" -Level "WARN"
}
}
else {
Write-Log ""
Write-Log "── Available Gen 1 VMs ──"
for ($i = 0; $i -lt $inventory.Count; $i++) {
$vm = $inventory[$i]
$checkpointFlag = if ($vm.CheckpointsExist -eq "True") { " ⚠️ HAS CHECKPOINTS" } else { "" }
Write-Host " [$i] $($vm.VMName) | State: $($vm.State) | Host: $($vm.Host)$checkpointFlag" -ForegroundColor White
}
Write-Host ""
$selection = Read-Host "Enter VM numbers to convert (comma-separated, e.g., 0,2,4) or 'all'"
if ($selection -eq 'all') {
$selectedVMs = $inventory
}
else {
$indices = $selection -split ',' | ForEach-Object { [int]$_.Trim() }
$selectedVMs = $indices | ForEach-Object { $inventory[$_] }
}
}
Write-Log ""
Write-Log "Selected $($selectedVMs.Count) VMs for conversion:"
$selectedVMs | ForEach-Object { Write-Log " - $($_.VMName)" }
# ── Pre-Flight Checks ───────────────────────────────────────────────────────
Write-Log ""
Write-Log "Running pre-flight checks..."
$readyVMs = @()
$skippedVMs = @()
foreach ($vmEntry in $selectedVMs) {
$vmName = $vmEntry.VMName
$issues = @()
try {
$vm = Get-VM -Name $vmName -ErrorAction Stop
if ($vm.State -ne 'Off') {
$issues += "VM is not shut down (State: $($vm.State))"
}
if ($vm.Generation -ne 1) {
$issues += "VM is already Gen $($vm.Generation)"
}
}
catch {
$issues += "VM not found: $_"
}
try {
$checkpoints = Get-VMCheckpoint -VMName $vmName -ErrorAction SilentlyContinue
if ($checkpoints.Count -gt 0) {
$issues += "Has $($checkpoints.Count) checkpoint(s) — must remove first"
}
}
catch { }
$configPath = Join-Path $WorkingDirectory "Configs\${vmName}_config.json"
if (-not (Test-Path $configPath)) {
$issues += "No config file found (run Script 01)"
}
if ($issues.Count -gt 0) {
Write-Log " SKIP: $vmName" -Level "WARN"
$issues | ForEach-Object { Write-Log " ⚠️ $_" -Level "WARN" }
$skippedVMs += [PSCustomObject]@{ VMName = $vmName; Reason = ($issues -join "; ") }
}
else {
Write-Log " READY: $vmName" -Level "SUCCESS"
$readyVMs += $vmEntry
}
}
if ($readyVMs.Count -eq 0) {
Write-Log "No VMs are ready for conversion!" -Level "ERROR"
throw "No VMs to process."
}
Write-Log ""
Write-Log "$($readyVMs.Count) VMs ready, $($skippedVMs.Count) skipped"
# Confirmation
Write-Host ""
Write-Host "╔═══════════════════════════════════════════════════════════════╗" -ForegroundColor Yellow
Write-Host "║ READY TO CONVERT $($readyVMs.Count) VMs FROM GEN 1 → GEN 2 ║" -ForegroundColor Yellow
Write-Host "║ ║" -ForegroundColor Yellow
Write-Host "║ This will: ║" -ForegroundColor Yellow
Write-Host "║ - Remove each Gen 1 VM ║" -ForegroundColor Yellow
Write-Host "║ - Create new Gen 2 VMs with the same disks ║" -ForegroundColor Yellow
Write-Host "╚═══════════════════════════════════════════════════════════════╝" -ForegroundColor Yellow
Write-Host ""
$confirm = Read-Host "Type 'CONVERT' to proceed"
if ($confirm -ne 'CONVERT') {
Write-Log "Batch conversion cancelled by user." -Level "WARN"
exit 0
}
# ── Process Each VM ──────────────────────────────────────────────────────────
Write-Log ""
Write-Log "Starting batch conversion..."
$results = @()
$totalCount = $readyVMs.Count
$currentIndex = 0
foreach ($vmEntry in $readyVMs) {
$currentIndex++
$vmName = $vmEntry.VMName
Write-Log ""
Write-Log "════════════════════════════════════════════════════"
Write-Log " [$currentIndex / $totalCount] Converting: $vmName"
Write-Log "════════════════════════════════════════════════════"
$startTime = Get-Date
$status = "SUCCESS"
$errorMsg = ""
try {
$convertScript = Join-Path $ScriptRoot "03-Convert-Gen1toGen2.ps1"
$params = @{
VMName = $vmName
WorkingDirectory = $WorkingDirectory
BackupVHDX = $true
Confirm = $false
}
& $convertScript @params
Write-Log " $vmName conversion completed" -Level "SUCCESS"
}
catch {
$status = "FAILED"
$errorMsg = $_.Exception.Message
Write-Log " $vmName conversion FAILED: $errorMsg" -Level "ERROR"
}
$duration = (Get-Date) - $startTime
$results += [PSCustomObject]@{
VMName = $vmName
Status = $status
Duration = $duration.ToString("hh\:mm\:ss")
Error = $errorMsg
CompletedAt = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
}
if ($currentIndex -lt $totalCount) {
Write-Log " Pausing 10 seconds before next VM..."
Start-Sleep -Seconds 10
}
}
# ── Generate Report ──────────────────────────────────────────────────────────
Write-Log ""
Write-Log "═══════════════════════════════════════════════════════════════"
Write-Log " BATCH CONVERSION REPORT"
Write-Log "═══════════════════════════════════════════════════════════════"
$successCount = ($results | Where-Object { $_.Status -eq "SUCCESS" }).Count
$failCount = ($results | Where-Object { $_.Status -eq "FAILED" }).Count
Write-Log " Total: $totalCount"
Write-Log " Success: $successCount" -Level "SUCCESS"
Write-Log " Failed: $failCount" -Level $(if ($failCount -gt 0) { "ERROR" } else { "SUCCESS" })
Write-Log " Skipped: $($skippedVMs.Count)" -Level $(if ($skippedVMs.Count -gt 0) { "WARN" } else { "SUCCESS" })
Write-Log ""
Write-Log "── Results ──"
foreach ($r in $results) {
$level = if ($r.Status -eq "SUCCESS") { "SUCCESS" } else { "ERROR" }
$msg = " $($r.VMName): $($r.Status) ($($r.Duration))"
if ($r.Error) { $msg += " — $($r.Error)" }
Write-Log $msg -Level $level
}
if ($skippedVMs.Count -gt 0) {
Write-Log ""
Write-Log "── Skipped VMs ──"
foreach ($s in $skippedVMs) {
Write-Log " $($s.VMName): $($s.Reason)" -Level "WARN"
}
}
$reportPath = Join-Path $WorkingDirectory "Logs\BatchReport_$(Get-Date -Format 'yyyyMMdd_HHmmss').csv"
$results | Export-Csv -Path $reportPath -NoTypeInformation
Write-Log ""
Write-Log " Report saved: $reportPath"
Write-Log " Log file: $BatchLogFile"
Write-Log "═══════════════════════════════════════════════════════════════"