-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputeAnalysis.ps1
More file actions
786 lines (706 loc) · 39 KB
/
Copy pathComputeAnalysis.ps1
File metadata and controls
786 lines (706 loc) · 39 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
param([string]$vCenterURL)
# Force UTF-8 output so PHP json_decode handles non-ASCII VM/DS names correctly.
# Wrapped in try/catch because [Console]::OutputEncoding throws "The handle is invalid"
# when PowerShell is invoked without an attached console (e.g. via PHP shell_exec).
try {
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
} catch { }
$ErrorActionPreference = "Continue"
$WarningPreference = "SilentlyContinue" # prevent warnings from polluting JSON stdout
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
$SnapshotAgeDays = 30 # snapshots older than this are flagged
$MigrationMemThreshold = 80 # host mem % above which migration is suggested
$MigrationTargetCap = 85 # never suggest a target exceeding this %
$AssumedVmCpuUtilization = 0.20 # assumed avg fraction of a VM's vCPUs actually in use
$JsonDepth = 10 # depth for nested JSON output
$NPlus1SafePct = 85 # after a single-host failure, survivors should stay under this %
$OldHWVersionNum = 14 # vmx-14 (vSphere 6.7) and below = legacy
$HWUpgradeVersionNum = 19 # vmx-19 (vSphere 7.0 U2) and below = upgrade available
$ExcludeClusters = @() # populate to skip specific clusters
# ---------------------------------------------------------------------------
# Find credentials file
# ---------------------------------------------------------------------------
$fallbackPaths = @(
(Join-Path $PSScriptRoot "vcenter.csv"),
"$env:USERPROFILE\Desktop\vcenter.csv"
)
$credFilePath = $null
foreach ($path in $fallbackPaths) {
if (Test-Path $path) { $credFilePath = $path; break }
}
if ($null -eq $credFilePath) {
Write-Output '{"success":false,"message":"Credentials file not found"}'
exit
}
# ---------------------------------------------------------------------------
# Configure PowerCLI
# ---------------------------------------------------------------------------
# -Scope Session avoids writing to the shared XML file (prevents lock contention when
# multiple vCenter requests run in parallel)
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Scope Session -Confirm:$false -WarningAction SilentlyContinue | Out-Null
# ---------------------------------------------------------------------------
# Load credentials
# ---------------------------------------------------------------------------
try {
$vcinfo = Import-Csv $credFilePath -ErrorAction Stop
if ($null -eq $vcinfo) {
Write-Output '{"success":false,"message":"Credentials file is empty"}'
exit
}
} catch {
Write-Output '{"success":false,"message":"Failed to load credentials"}'
exit
}
$credentials = $vcinfo | Where-Object { $_.viserver.Trim() -eq $vCenterURL.Trim() }
if ($null -eq $credentials) {
Write-Output '{"success":false,"message":"vCenter not found"}'
exit
}
# ---------------------------------------------------------------------------
# Connect to vCenter
# ---------------------------------------------------------------------------
$connection = $null
try {
$connection = Connect-VIServer -Server $credentials.viserver -User $credentials.username `
-Password $credentials.password -ErrorAction Stop -WarningAction SilentlyContinue
} catch {
Write-Output '{"success":false,"message":"Failed to connect"}'
exit
}
# ---------------------------------------------------------------------------
# Helper functions
# ---------------------------------------------------------------------------
function Get-HostCoreCount {
param($VmHost)
$cpuInfo = $VmHost.ExtensionData.Hardware.CpuInfo
if ($null -ne $cpuInfo -and $cpuInfo.NumCpuCores -gt 0) { return [int]$cpuInfo.NumCpuCores }
return 0
}
function Get-HostThreadCount {
param($VmHost)
$cpuInfo = $VmHost.ExtensionData.Hardware.CpuInfo
if ($null -ne $cpuInfo -and $cpuInfo.NumCpuThreads -gt 0) { return [int]$cpuInfo.NumCpuThreads }
return 0
}
function Get-EVCFamily {
param([string]$EVCKey)
if ([string]::IsNullOrEmpty($EVCKey)) { return '' }
if ($EVCKey -match '^(intel|amd)') { return $Matches[1] }
return ''
}
# ---------------------------------------------------------------------------
# Initialize analysis output
# ---------------------------------------------------------------------------
$Analysis = @{
success = $true
vCenter = $vCenterURL
Clusters = @()
Errors = @()
generatedAt = (Get-Date -Format "yyyy-MM-dd HH:mm:ss")
}
try {
# ---------------------------------------------------------------------------
# Build global infrastructure maps (required for cross-cluster migration)
# ---------------------------------------------------------------------------
$AllClusters = @(Get-Cluster -ErrorAction Stop | Where-Object { $ExcludeClusters -notcontains $_.Name })
if ($AllClusters.Count -eq 0) {
Write-Output '{"success":false,"message":"No clusters found"}'
exit
}
# All connected hosts across all clusters
$AllHosts = @(Get-VMHost -ErrorAction SilentlyContinue | Where-Object { $_.ConnectionState -eq "Connected" })
# Map: hostName -> clusterName (via each host's Parent cluster object — no extra API calls)
$HostClusterMap = @{}
foreach ($h in $AllHosts) {
if ($null -ne $h.Parent) {
$HostClusterMap[$h.Name] = $h.Parent.Name
}
}
# Map: clusterName -> EVC mode key (e.g. "intel-haswell", "amd-milan", or "")
$ClusterEVCMap = @{}
foreach ($cluster in $AllClusters) {
$evcKey = $cluster.ExtensionData.Summary.CurrentEVCModeKey
$ClusterEVCMap[$cluster.Name] = if ($null -ne $evcKey) { [string]$evcKey } else { '' }
}
# Map: hostName -> [port group names] (standard vSwitch + distributed vSwitch)
$HostNetworkMap = @{}
foreach ($h in $AllHosts) {
$pgNames = [System.Collections.Generic.List[string]]::new()
$stdPGs = @(Get-VirtualPortGroup -VMHost $h -ErrorAction SilentlyContinue)
foreach ($pg in $stdPGs) {
if (-not [string]::IsNullOrEmpty($pg.Name)) { $pgNames.Add($pg.Name) }
}
# Distributed port groups require the VDS module; skip gracefully if absent
try {
$dvPGs = @(Get-VDPortgroup -VMHost $h -ErrorAction SilentlyContinue)
foreach ($pg in $dvPGs) {
if (-not [string]::IsNullOrEmpty($pg.Name)) { $pgNames.Add($pg.Name) }
}
} catch { }
$HostNetworkMap[$h.Name] = @($pgNames | Sort-Object -Unique)
}
# Map: hostName -> [datastore names accessible from that host]
$HostDatastoreMap = @{}
foreach ($h in $AllHosts) {
$ds = @(Get-Datastore -VMHost $h -ErrorAction SilentlyContinue)
$HostDatastoreMap[$h.Name] = @($ds | ForEach-Object { $_.Name })
}
# ---------------------------------------------------------------------------
# Per-cluster analysis loop
# ---------------------------------------------------------------------------
foreach ($cluster in $AllClusters) {
try {
$allClusterHosts = @($cluster | Get-VMHost -ErrorAction Stop)
$hosts = @($allClusterHosts | Where-Object { $_.ConnectionState -eq "Connected" })
$allClusterVMs = @($cluster | Get-VM -ErrorAction Stop)
$vms = @($allClusterVMs | Where-Object { $_.PowerState -eq "PoweredOn" })
$poweredOffVMs = @($allClusterVMs | Where-Object { $_.PowerState -eq "PoweredOff" })
# ----------------------------------------------------------------
# Snapshots
# ----------------------------------------------------------------
$snapCount = 0
$oldSnapCount = 0
$snapshotInfo = @()
if ($vms.Count -gt 0) {
$allSnapshots = @($vms | Get-Snapshot -ErrorAction SilentlyContinue)
$snapCount = $allSnapshots.Count
$ageThreshold = (Get-Date).AddDays(-$SnapshotAgeDays)
$oldSnapshots = @($allSnapshots | Where-Object { $_.Created -lt $ageThreshold })
$oldSnapCount = $oldSnapshots.Count
if ($oldSnapshots.Count -gt 0) {
$snapshotInfo = @($oldSnapshots | Select-Object -First 5 | ForEach-Object {
$ageInDays = [Math]::Floor(((Get-Date) - $_.Created).TotalDays)
@{ Name = $_.Name; VM = $_.VM.Name; Created = $_.Created.ToString("yyyy-MM-dd"); AgeInDays = $ageInDays }
})
}
}
# ----------------------------------------------------------------
# Powered-off VM inventory (top 15 by allocated memory)
# ----------------------------------------------------------------
$poweredOffInfo = @($poweredOffVMs | Sort-Object -Property MemoryGB -Descending | Select-Object -First 15 | ForEach-Object {
$hwNum = 0
if ($_.HardwareVersion -match 'v?(\d+)') { $hwNum = [int]$Matches[1] }
@{
Name = $_.Name
CPU = $_.NumCpu
Memory = [Math]::Round($_.MemoryGB, 1)
HWVer = $_.HardwareVersion.ToString()
HWNum = $hwNum
}
})
# ----------------------------------------------------------------
# VM health issues: tools, HW version, CD/DVD media, hot-add
# Batch fetches to minimize API round trips.
# ----------------------------------------------------------------
$toolsIssues = @()
$hwIssues = @()
$mediaIssues = @()
$hotAddIssues = @()
$nicsByVM = @{}
$disksByVM = @{}
if ($vms.Count -gt 0) {
# Batch API calls
$allNics = @(Get-NetworkAdapter -VM $vms -ErrorAction SilentlyContinue)
$allDisks = @(Get-HardDisk -VM $vms -ErrorAction SilentlyContinue)
$allCDs = @(Get-CDDrive -VM $vms -ErrorAction SilentlyContinue)
# Index by VM name
foreach ($nic in $allNics) {
$n = $nic.Parent.Name
if (-not $nicsByVM.ContainsKey($n)) { $nicsByVM[$n] = [System.Collections.Generic.List[object]]::new() }
$nicsByVM[$n].Add($nic)
}
foreach ($disk in $allDisks) {
$n = $disk.Parent.Name
if (-not $disksByVM.ContainsKey($n)) { $disksByVM[$n] = [System.Collections.Generic.List[object]]::new() }
$disksByVM[$n].Add($disk)
}
$cdsByVM = @{}
foreach ($cd in $allCDs) {
$n = $cd.Parent.Name
if (-not $cdsByVM.ContainsKey($n)) { $cdsByVM[$n] = [System.Collections.Generic.List[object]]::new() }
$cdsByVM[$n].Add($cd)
}
foreach ($vm in $vms) {
# VMware Tools status
$toolsStatus = $vm.ExtensionData.Guest.ToolsStatus
$toolsStr = if ($null -ne $toolsStatus) { $toolsStatus.ToString() } else { 'toolsNotInstalled' }
$toolsVer = $vm.ExtensionData.Guest.ToolsVersion
if ($toolsStr -ne 'toolsOk') {
$toolsVerStr = if ($null -ne $toolsVer) { $toolsVer.ToString() } else { 'N/A' }
$toolsIssues += @{
VM = $vm.Name
Status = $toolsStr
Version = $toolsVerStr
}
}
# Virtual hardware version
$hwVerStr = $vm.HardwareVersion.ToString()
$hwNum = 0
if ($hwVerStr -match 'v?(\d+)') { $hwNum = [int]$Matches[1] }
if ($hwNum -gt 0 -and $hwNum -lt $HWUpgradeVersionNum) {
$hwSeverity = if ($hwNum -lt $OldHWVersionNum) { 'Legacy' } else { 'Upgrade Available' }
$hwIssues += @{
VM = $vm.Name
HWVer = $hwVerStr
HWNum = $hwNum
Severity = $hwSeverity
}
}
# CD/DVD media connected
if ($cdsByVM.ContainsKey($vm.Name)) {
foreach ($cd in $cdsByVM[$vm.Name]) {
if ($cd.ConnectionState.Connected) {
$iso = if (-not [string]::IsNullOrEmpty($cd.IsoPath)) { $cd.IsoPath } else { 'Physical/Host Device' }
$mediaIssues += @{ VM = $vm.Name; Media = $iso }
break
}
}
}
# CPU / Memory hot-add disabled
$cpuHA = $vm.ExtensionData.Config.CpuHotAddEnabled
$memHA = $vm.ExtensionData.Config.MemoryHotAddEnabled
if (-not $cpuHA -or -not $memHA) {
$hotAddIssues += @{
VM = $vm.Name
CPU = $vm.NumCpu
Memory = [Math]::Round($vm.MemoryGB, 1)
CPUHotAdd = [bool]$cpuHA
MemHotAdd = [bool]$memHA
}
}
}
}
# ----------------------------------------------------------------
# Datastore capacity (sorted by usage descending)
# ----------------------------------------------------------------
$datastoreInfo = @()
$clusterDSList = @(Get-Datastore -RelatedObject $cluster -ErrorAction SilentlyContinue)
foreach ($ds in $clusterDSList) {
$capGB = [Math]::Round($ds.CapacityGB, 0)
$freeGB = [Math]::Round($ds.FreeSpaceGB, 0)
$usedGB = $capGB - $freeGB
$usagePct = if ($capGB -gt 0) { [Math]::Round(($usedGB / $capGB) * 100, 1) } else { 0 }
$datastoreInfo += @{
Name = $ds.Name
Type = $ds.Type
CapGB = $capGB
FreeGB = $freeGB
UsagePct = $usagePct
}
}
$datastoreInfo = @($datastoreInfo | Sort-Object -Property UsagePct -Descending)
# ----------------------------------------------------------------
# Cluster-level capacity metrics
# ----------------------------------------------------------------
$totalCpuMhz = 0; $usedCpuMhz = 0
$totalMemGB = 0; $usedMemGB = 0
$totalCores = 0; $totalThreads = 0
if ($hosts.Count -gt 0) {
$totalCpuMhz = ($hosts | Measure-Object -Property CpuTotalMhz -Sum -ErrorAction SilentlyContinue).Sum
$usedCpuMhz = ($hosts | Measure-Object -Property CpuUsageMhz -Sum -ErrorAction SilentlyContinue).Sum
$totalMemGB = ($hosts | Measure-Object -Property MemoryTotalGB -Sum -ErrorAction SilentlyContinue).Sum
$usedMemGB = ($hosts | Measure-Object -Property MemoryUsageGB -Sum -ErrorAction SilentlyContinue).Sum
foreach ($h in $hosts) {
$totalCores += Get-HostCoreCount -VmHost $h
$totalThreads += Get-HostThreadCount -VmHost $h
}
}
$provCpu = 0; $provMem = 0
if ($vms.Count -gt 0) {
$provCpu = ($vms | Measure-Object -Property NumCpu -Sum -ErrorAction SilentlyContinue).Sum
$provMem = ($vms | Measure-Object -Property MemoryGB -Sum -ErrorAction SilentlyContinue).Sum
}
$vmDensity = if ($hosts.Count -gt 0) { [Math]::Round($vms.Count / $hosts.Count, 1) } else { 0 }
$avgVmWeight = if ($vms.Count -gt 0) { [Math]::Round($usedMemGB / $vms.Count, 1) } else { 0 }
$availCpuCores = [Math]::Max(0, $totalCores - $provCpu)
$availMemGB = [Math]::Max(0, $totalMemGB - $provMem)
$cpuUsage = if ($totalCpuMhz -gt 0) { [Math]::Round(($usedCpuMhz / $totalCpuMhz) * 100, 1) } else { 0 }
$memUsage = if ($totalMemGB -gt 0) { [Math]::Round(($usedMemGB / $totalMemGB ) * 100, 1) } else { 0 }
# ----------------------------------------------------------------
# N+1 redundancy analysis
# ----------------------------------------------------------------
$vCpuRatio = if ($totalCores -gt 0) { [Math]::Round($provCpu / $totalCores, 2) } else { 0 }
$nPlus1Status = 'N/A'
$worstMemAfterPct = 0; $worstCpuAfterPct = 0; $worstFailHost = $null
if ($hosts.Count -ge 2) {
foreach ($failHost in $hosts) {
$remMemGB = $totalMemGB - $failHost.MemoryTotalGB
$remCpuMhz = $totalCpuMhz - $failHost.CpuTotalMhz
$projMemPct = if ($remMemGB -gt 0) { ($usedMemGB / $remMemGB ) * 100 } else { 999 }
$projCpuPct = if ($remCpuMhz -gt 0) { ($usedCpuMhz / $remCpuMhz) * 100 } else { 999 }
if ($projMemPct -gt $worstMemAfterPct) { $worstMemAfterPct = $projMemPct; $worstFailHost = $failHost.Name }
if ($projCpuPct -gt $worstCpuAfterPct) { $worstCpuAfterPct = $projCpuPct }
}
$worstMemAfterPct = [Math]::Round($worstMemAfterPct, 1)
$worstCpuAfterPct = [Math]::Round($worstCpuAfterPct, 1)
if ($worstMemAfterPct -le $NPlus1SafePct -and $worstCpuAfterPct -le $NPlus1SafePct) { $nPlus1Status = 'Safe' }
elseif ($worstMemAfterPct -le 100 -and $worstCpuAfterPct -le 100) { $nPlus1Status = 'At Risk' }
else { $nPlus1Status = 'Insufficient' }
}
# ----------------------------------------------------------------
# Composite health score
# ----------------------------------------------------------------
$score = 100
if ($memUsage -gt 85) { $score -= 25 }
elseif ($memUsage -gt 75) { $score -= 10 }
if ($snapCount -gt 20) { $score -= 5 }
if ($nPlus1Status -eq 'At Risk') { $score -= 10 }
if ($nPlus1Status -eq 'Insufficient') { $score -= 20 }
if ($toolsIssues.Count -gt 5) { $score -= 5 }
if ($mediaIssues.Count -gt 0) { $score -= 5 }
if ($score -lt 0) { $score = 0 }
# ----------------------------------------------------------------
# Top 5 VMs by configured memory
# ----------------------------------------------------------------
$topVMs = @()
if ($vms.Count -gt 0) {
$topVMs = @($vms | Sort-Object -Property MemoryGB -Descending | Select-Object -First 5 | ForEach-Object {
@{ Name = $_.Name; CPU = $_.NumCpu; Memory = [Math]::Round($_.MemoryGB, 1) }
})
}
# ----------------------------------------------------------------
# Per-host analysis with cross-cluster migration
# ----------------------------------------------------------------
$sourceClusterName = $cluster.Name
$sourceEVC = $ClusterEVCMap[$sourceClusterName]
$sourceEVCFamily = Get-EVCFamily -EVCKey $sourceEVC
$hostDetails = @()
# Add non-connected hosts as stubs so the UI can show their state
foreach ($vmhost in $allClusterHosts) {
if ($vmhost.ConnectionState -ne "Connected") {
$stubBootTime = $vmhost.ExtensionData.Summary.Runtime.BootTime
$stubUptimeDays = -1
if ($null -ne $stubBootTime -and $stubBootTime.Year -gt 2000) {
$stubUptimeDays = [Math]::Round(((Get-Date).ToUniversalTime() - $stubBootTime).TotalDays, 0)
}
$stubHWStatus = 'unknown'
if ($null -ne $vmhost.ExtensionData.Summary.OverallStatus) {
$stubHWStatus = $vmhost.ExtensionData.Summary.OverallStatus.ToString().ToLower()
}
$hostDetails += @{
HostName = $vmhost.Name
ConnectionState = $vmhost.ConnectionState.ToString()
CoreCount = (Get-HostCoreCount -VmHost $vmhost)
CpuUsage = 0
MemUsage = 0
UptimeDays = $stubUptimeDays
OverallStatus = $stubHWStatus
TopVM = $null
MigrationSuggestion = $null
}
}
}
foreach ($vmhost in $hosts) {
$hostCpuUsage = if ($vmhost.CpuTotalMhz -gt 0) { [Math]::Round(($vmhost.CpuUsageMhz / $vmhost.CpuTotalMhz ) * 100, 1) } else { 0 }
$hostMemUsage = if ($vmhost.MemoryTotalGB -gt 0) { [Math]::Round(($vmhost.MemoryUsageGB / $vmhost.MemoryTotalGB) * 100, 1) } else { 0 }
$hostCores = Get-HostCoreCount -VmHost $vmhost
# Uptime and hardware health
$hostBootTime = $vmhost.ExtensionData.Summary.Runtime.BootTime
$hostUptimeDays = -1
if ($null -ne $hostBootTime -and $hostBootTime.Year -gt 2000) {
$hostUptimeDays = [Math]::Round(((Get-Date).ToUniversalTime() - $hostBootTime).TotalDays, 0)
}
$hostHWStatus = 'unknown'
if ($null -ne $vmhost.ExtensionData.Summary.OverallStatus) {
$hostHWStatus = $vmhost.ExtensionData.Summary.OverallStatus.ToString().ToLower()
}
# Heaviest VM on this host (migration candidate)
$topVmOnHost = $null
$hostVm = $vms | Where-Object { $_.VMHost.Name -eq $vmhost.Name } | Sort-Object -Property MemoryGB -Descending | Select-Object -First 1
if ($null -ne $hostVm) {
$topVmOnHost = @{ Name = $hostVm.Name; CPU = $hostVm.NumCpu; Memory = [Math]::Round($hostVm.MemoryGB, 1) }
}
# Migration suggestion (searches across all clusters)
$migrationSuggestion = $null
if ($hostMemUsage -gt $MigrationMemThreshold -and $null -ne $topVmOnHost) {
# Resolve the VM's network and datastore requirements from pre-fetched data
$vmNetworks = @()
$vmDSNames = @()
if ($nicsByVM.ContainsKey($topVmOnHost.Name)) {
$vmNetworks = @($nicsByVM[$topVmOnHost.Name] | ForEach-Object { $_.NetworkName } |
Where-Object { $_ -ne $null } | Sort-Object -Unique)
}
if ($disksByVM.ContainsKey($topVmOnHost.Name)) {
$vmDSNames = @($disksByVM[$topVmOnHost.Name] | ForEach-Object {
if ($_.Filename -match '^\[(.+?)\]') { $Matches[1] }
} | Where-Object { $_ -ne $null } | Sort-Object -Unique)
}
$bestTarget = $null
$bestScore = 999
$bestIsCrossCluster = $false
$bestTargetCluster = $null
foreach ($targetHost in $AllHosts) {
if ($targetHost.Name -eq $vmhost.Name) { continue }
$targetClusterName = $HostClusterMap[$targetHost.Name]
if ($null -eq $targetClusterName) { continue }
$isCrossCluster = ($targetClusterName -ne $sourceClusterName)
# Resource headroom check
$tMemUsage = if ($targetHost.MemoryTotalGB -gt 0) { [Math]::Round(($targetHost.MemoryUsageGB / $targetHost.MemoryTotalGB) * 100, 1) } else { 0 }
$tCpuUsage = if ($targetHost.CpuTotalMhz -gt 0) { [Math]::Round(($targetHost.CpuUsageMhz / $targetHost.CpuTotalMhz ) * 100, 1) } else { 0 }
$tCores = Get-HostCoreCount -VmHost $targetHost
$tMemAfter = if ($targetHost.MemoryTotalGB -gt 0) { $tMemUsage + (($topVmOnHost.Memory / $targetHost.MemoryTotalGB) * 100) } else { 100 }
$cpuDemand = $topVmOnHost.CPU * $AssumedVmCpuUtilization
$tCpuContrib = if ($tCores -gt 0) { ($cpuDemand / $tCores) * 100 } else { 100 }
$tCpuAfter = $tCpuUsage + $tCpuContrib
if ($tMemAfter -gt $MigrationTargetCap) { continue }
if ($tCpuAfter -gt $MigrationTargetCap) { continue }
# Cross-cluster compatibility gate
if ($isCrossCluster) {
$compat = $true
# All VM networks must exist on the target host
$targetNets = $HostNetworkMap[$targetHost.Name]
if ($null -eq $targetNets) { $targetNets = @() }
foreach ($net in $vmNetworks) {
if ($net -notin $targetNets) { $compat = $false; break }
}
if (-not $compat) { continue }
# All VM datastores must be accessible from the target host
$targetDSList = $HostDatastoreMap[$targetHost.Name]
if ($null -eq $targetDSList) { $targetDSList = @() }
foreach ($ds in $vmDSNames) {
if ($ds -notin $targetDSList) { $compat = $false; break }
}
if (-not $compat) { continue }
# CPU family must match (intel-* vs amd-*) when both clusters have EVC set
$targetEVC = $ClusterEVCMap[$targetClusterName]
$targetEVCFamily = Get-EVCFamily -EVCKey $targetEVC
if ($sourceEVCFamily -ne '' -and $targetEVCFamily -ne '' -and $sourceEVCFamily -ne $targetEVCFamily) {
continue
}
}
# Rank by balanced load; prefer same-cluster slightly
$rankScore = ($tMemAfter + $tCpuAfter) / 2
if ($isCrossCluster) { $rankScore += 3 }
if ($rankScore -lt $bestScore) {
$bestScore = $rankScore
$bestIsCrossCluster = $isCrossCluster
$bestTargetCluster = $targetClusterName
$bestTarget = @{
HostName = $targetHost.Name
CurrentMemUsage = $tMemUsage
CurrentCpuUsage = $tCpuUsage
}
}
}
if ($null -ne $bestTarget) {
$migReason = if ($bestIsCrossCluster) {
"Cross-cluster to '$bestTargetCluster': CPU $($bestTarget.CurrentCpuUsage)%, Mem $($bestTarget.CurrentMemUsage)% - networks and datastores verified"
} else {
"Same-cluster: CPU $($bestTarget.CurrentCpuUsage)%, Mem $($bestTarget.CurrentMemUsage)%"
}
$migrationSuggestion = @{
TargetHost = $bestTarget.HostName
TargetCluster = $bestTargetCluster
CrossCluster = $bestIsCrossCluster
VMNetworks = $vmNetworks
VMDatastores = $vmDSNames
Reason = $migReason
Available = $true
}
} else {
$migrationSuggestion = @{
TargetHost = $null
TargetCluster = $null
CrossCluster = $false
VMNetworks = $vmNetworks
VMDatastores = $vmDSNames
Reason = "No suitable target found across all clusters - verify shared networks and datastores"
Available = $false
}
}
}
$hostDetails += @{
HostName = $vmhost.Name
ConnectionState = $vmhost.ConnectionState.ToString()
CoreCount = $hostCores
CpuUsage = $hostCpuUsage
MemUsage = $hostMemUsage
UptimeDays = $hostUptimeDays
OverallStatus = $hostHWStatus
TopVM = $topVmOnHost
MigrationSuggestion = $migrationSuggestion
}
}
# ----------------------------------------------------------------
# ESXi version consistency
# Base version = the most recent ESXi version+build present on any
# connected host. Any host below that base is flagged so the whole
# cluster can be kept on a single, most-recent version.
# ----------------------------------------------------------------
$esxiEntries = @()
$baseVerObj = [version]'0.0.0'
$baseBuildNum = [int64]0
$haveAnyVer = $false
foreach ($vmhost in $hosts) {
$prod = $vmhost.ExtensionData.Config.Product
$verStr = ''
$buildStr = ''
if ($null -ne $prod) {
if (-not [string]::IsNullOrEmpty($prod.Version)) { $verStr = $prod.Version.ToString() }
if (-not [string]::IsNullOrEmpty($prod.Build)) { $buildStr = $prod.Build.ToString() }
}
# Fall back to the flat VMHost properties if ExtensionData is sparse
if ($verStr -eq '' -and $null -ne $vmhost.Version) { $verStr = $vmhost.Version.ToString() }
if ($buildStr -eq '' -and $null -ne $vmhost.Build) { $buildStr = $vmhost.Build.ToString() }
$verObj = [version]'0.0.0'
try { if ($verStr -ne '') { $verObj = [version]$verStr } } catch { $verObj = [version]'0.0.0' }
$buildNum = [int64]0
if ($buildStr -match '^\d+$') { $buildNum = [int64]$buildStr }
$display = if ($verStr -ne '') {
if ($buildStr -ne '') { "$verStr (build $buildStr)" } else { $verStr }
} else { 'Unknown' }
$esxiEntries += @{
HostName = $vmhost.Name
Version = $verStr
Build = $buildStr
Display = $display
VerObj = $verObj
BuildNum = $buildNum
}
$haveAnyVer = $true
if ($verObj -gt $baseVerObj -or ($verObj -eq $baseVerObj -and $buildNum -gt $baseBuildNum)) {
$baseVerObj = $verObj
$baseBuildNum = $buildNum
}
}
# Resolve the base entry's original strings for display
$baseVerStr = ''
$baseBuildStr = ''
$baseDisplay = 'N/A'
if ($haveAnyVer) {
foreach ($e in $esxiEntries) {
if ($e.VerObj -eq $baseVerObj -and $e.BuildNum -eq $baseBuildNum) {
$baseVerStr = $e.Version
$baseBuildStr = $e.Build
$baseDisplay = $e.Display
break
}
}
}
# Per-host flags + distinct-version count (excludes the internal sort keys)
$esxiHostList = @()
$esxiUpgradeHosts = @()
$distinctVersions = @{}
foreach ($e in $esxiEntries) {
$needsUpgrade = ($e.VerObj -lt $baseVerObj) -or ($e.VerObj -eq $baseVerObj -and $e.BuildNum -lt $baseBuildNum)
if ($e.Display -ne 'Unknown') { $distinctVersions[$e.Display] = $true }
$esxiHostList += @{
HostName = $e.HostName
Version = $e.Version
Build = $e.Build
Display = $e.Display
NeedsUpgrade = [bool]$needsUpgrade
}
if ($needsUpgrade) { $esxiUpgradeHosts += $e.HostName }
}
$esxiConsistent = ($esxiUpgradeHosts.Count -eq 0)
if (-not $haveAnyVer) {
$esxiRecommendation = 'No connected hosts available to evaluate ESXi versions.'
} elseif ($esxiConsistent) {
$esxiRecommendation = "All $($esxiHostList.Count) host(s) are running ESXi $baseDisplay. Cluster is version-consistent; no action required."
} else {
$upgradeNames = $esxiUpgradeHosts -join ', '
$esxiRecommendation = "$($esxiUpgradeHosts.Count) of $($esxiHostList.Count) host(s) are running an older ESXi version. Upgrade to the cluster baseline ESXi ${baseDisplay}: $upgradeNames. Keep all hosts on the same ESXi version, using the most recent version currently present in the cluster as the target baseline."
}
$esxiVersionAnalysis = @{
BaseVersion = $baseVerStr
BaseBuild = $baseBuildStr
BaseDisplay = $baseDisplay
Consistent = [bool]$esxiConsistent
DistinctVersions = $distinctVersions.Keys.Count
UpgradeCount = $esxiUpgradeHosts.Count
HostCount = $esxiHostList.Count
Hosts = $esxiHostList
Recommendation = $esxiRecommendation
}
# ----------------------------------------------------------------
# HA / DRS / Active alarms
# ----------------------------------------------------------------
$haEnabled = ($cluster.ExtensionData.Configuration.DasConfig.Enabled -eq $true)
$drsEnabled = ($cluster.ExtensionData.Configuration.DrsConfig.Enabled -eq $true)
$drsModeName = 'Unknown'
if ($drsEnabled) {
$drsModeRaw = $cluster.ExtensionData.Configuration.DrsConfig.DefaultVmBehavior
if ($null -ne $drsModeRaw) {
switch ($drsModeRaw.ToString()) {
'fullyAutomated' { $drsModeName = 'Fully Automated' }
'partiallyAutomated' { $drsModeName = 'Partially Automated' }
'manual' { $drsModeName = 'Manual' }
default { $drsModeName = $drsModeRaw.ToString() }
}
}
}
$redAlarmCount = 0
if ($null -ne $cluster.ExtensionData.TriggeredAlarmState) {
foreach ($alarm in $cluster.ExtensionData.TriggeredAlarmState) {
if ($alarm.OverallStatus -eq 'red') { $redAlarmCount++ }
}
}
# ----------------------------------------------------------------
# Add cluster to analysis output
# ----------------------------------------------------------------
$Analysis.Clusters += @{
Name = $cluster.Name
HealthScore = [int]$score
CpuUsage = $cpuUsage
MemUsage = $memUsage
TotalCpuAssigned = [int]$provCpu
TotalCpuAvailable = [int]$totalCores
TotalPhysicalCores = [int]$totalCores
TotalLogicalThreads = [int]$totalThreads
vCpuRatio = $vCpuRatio
NPlus1Status = $nPlus1Status
NPlus1Detail = @{
MemUsedPctAfterFailure = $worstMemAfterPct
CpuUsedPctAfterFailure = $worstCpuAfterPct
WorstCaseHost = $worstFailHost
SafeThresholdPct = $NPlus1SafePct
}
TotalMemoryAssigned = [Math]::Round($provMem, 1)
TotalMemoryAvailable = [Math]::Round($totalMemGB, 1)
AvailableCpuCores = $availCpuCores
AvailableMemoryGB = [Math]::Round($availMemGB, 1)
VmDensity = $vmDensity
HostCount = $allClusterHosts.Count
VmCount = $vms.Count
AvgVmWeight = "$avgVmWeight GB"
SnapshotCount = $snapCount
OldSnapshotCount = $oldSnapCount
SnapshotDetails = $snapshotInfo
PoweredOffCount = $poweredOffVMs.Count
PoweredOffVMs = $poweredOffInfo
ToolsIssues = $toolsIssues
HWIssues = $hwIssues
MediaMounted = $mediaIssues
HotAddIssues = $hotAddIssues
Datastores = $datastoreInfo
EsxiVersion = $esxiVersionAnalysis
TopVMs = $topVMs
Hosts = $hostDetails
HAEnabled = $haEnabled
DRSEnabled = $drsEnabled
DRSMode = $drsModeName
RedAlarmCount = $redAlarmCount
ConnectedHosts = $hosts.Count
}
} catch {
# One bad cluster should not discard the entire analysis
$Analysis.Errors += @{ Cluster = $cluster.Name; Message = $_.Exception.Message }
continue
}
}
if ($Analysis.Clusters.Count -eq 0) { $Analysis.success = $false }
$Analysis | ConvertTo-Json -Depth $JsonDepth
} catch {
Write-Output "{`"success`":false,`"message`":$($_.Exception.Message | ConvertTo-Json)}"
exit
} finally {
try {
if ($null -ne $connection) {
Disconnect-VIServer -Server $connection -Force -Confirm:$false -ErrorAction SilentlyContinue | Out-Null
}
} catch { }
}