-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-GetHealthCode.ps1
More file actions
1985 lines (1693 loc) · 71.9 KB
/
Update-GetHealthCode.ps1
File metadata and controls
1985 lines (1693 loc) · 71.9 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
<#
.SYNOPSIS
Ensures all health-check scripts and PS Modules are installed & up-to-date.
.DESCRIPTION
Missing files are created. Existing files that differ are replaced.
Identical files are left unchanged. If this script updates itself,
it re-invokes the updated copy. When replacing a file, backup copies
are created in the backups directory.
Will set PSGallery as Trusted.
The updater also tracks a small "release marker" for the currently
installed code and for the target update source. A release marker is a
stable identifier for a specific release source, typically derived from
GitHub release metadata or from a manually supplied zip file name plus
its content hash. These markers are cached locally and let the updater
decide whether the requested update is already installed, whether it can
skip re-downloading or reapplying files, and when `-Reinstall` should
force the update to run again.
.PARAMETER Reinstall
Forces reinstall even when installed release matches target release.
.PARAMETER UpdateFromZip
Overides the default which is to fetch the latest GitHub release.
.PARAMETER Version
Explicit semantic version to associate with `-UpdateFromZip` when the zip
file name does not already embed a version token such as `v4.4.3`.
Use `X.Y.Z` or `vX.Y.Z`.
.PARAMETER ForceRefreshReleaseMetadata
Overides the default which is to cache latest-release metadata locally
for a few minutes (to avoid querying GitHub on every run).
.PARAMETER SelfRerunCount
Internal use only. Tracks the one-time self-rerun pass count.
.PARAMETER PersistReleaseMarker
Internal use only. Carries the resolved release marker across self-rerun.
.EXAMPLE
.\Update-GetHealthCode.ps1
Checks the locally cached latest-release metadata, refreshes it from
GitHub when needed, and installs the latest published release when it is
newer than the currently installed release marker.
.EXAMPLE
.\Update-GetHealthCode.ps1 -UpdateFromZip C:\Downloads\GetComputerHealth-v4.4.3.zip
#>
[CmdletBinding()]
param(
[switch]$Reinstall,
[string]$UpdateFromZip,
[string]$Version,
[switch]$ForceRefreshReleaseMetadata,
[Parameter(DontShow=$true)][int]$SelfRerunCount = 0,
[Parameter(DontShow=$true)][string]$PersistReleaseMarker
)
####################################################################
#
# START OF CONFIG
#
$SCRIPT_BIN_DIR = (Resolve-Path -LiteralPath $PSScriptRoot).Path
if ((Split-Path -Leaf $SCRIPT_BIN_DIR) -ine 'bin') {
throw "Refusing to run. Update-GetHealthCode.ps1 must be located in and executed from a 'bin' folder. Current script location: '$SCRIPT_BIN_DIR'."
}
$ROOT_DIR = Split-Path -Parent $SCRIPT_BIN_DIR
$DEST_DIR = $SCRIPT_BIN_DIR
$BAK_DIR = Join-Path $ROOT_DIR 'temp'
$CFG_DIR = Join-Path $ROOT_DIR 'config'
$LOG_DIR = Join-Path $ROOT_DIR 'log'
$script:UpdateTranscriptStarted = $false
$script:UpdateTranscriptTempPath = $null
$script:UpdateTranscriptFinalPath = $null
$script:UpdateTranscriptTimestamp = (Get-Date)
$REPO_URL = 'https://github.com/ndemou/GetComputerHealth'
$SHOW_AS_POSTPONED_WINDOW_DAYS = 150
$REPO_REF = 'main'
$GCH_CONFIG_PATH = Join-Path $CFG_DIR 'gch.psd1'
$LATEST_RELEASE_METADATA_CACHE_PATH = Join-Path $CFG_DIR 'Get-ComputerHealth-latest-release-meta.json'
$RELEASE_METADATA_CACHE_TTL_MINUTES = 60
$ZIP_CACHE_PATTERN = 'GetComputerHealth-release-*.zip'
$MANUAL_ZIP_CACHE_PATTERN = 'GetComputerHealth-MANUAL-UPDATE-*.zip'
$repoSlug = $null
#
# END OF CONFIG
#
####################################################################
####################################################################
#
# HELPER FUNCTIONS START
#
function Write-UpdateEvent {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Message)
if ([string]::IsNullOrWhiteSpace($Message)) { return }
Write-Host $Message
}
function Get-GchDefaultConfigText {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RepoUrl,
[Parameter(Mandatory)][int]$ShowAsPostponedWindowDays
)
@"
@{
AutomaticUpdates = `$true
RepoUrl = '$RepoUrl'
ShowAsPostponedWindowDays = $ShowAsPostponedWindowDays
}
"@
}
function Ensure-GchConfigFile {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$RepoUrl,
[Parameter(Mandatory)][int]$ShowAsPostponedWindowDays
)
if (Test-Path -LiteralPath $Path -PathType Leaf) {
return
}
$parentDir = Split-Path -Parent $Path
if (-not [string]::IsNullOrWhiteSpace($parentDir) -and (-not (Test-Path -LiteralPath $parentDir -PathType Container))) {
$null = New-Item -ItemType Directory -Path $parentDir -Force
}
$text = Get-GchDefaultConfigText -RepoUrl $RepoUrl -ShowAsPostponedWindowDays $ShowAsPostponedWindowDays
Set-Content -LiteralPath $Path -Value $text -Encoding UTF8
}
function Read-GchConfigFile {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return @{}
}
try {
$config = Import-PowerShellDataFile -LiteralPath $Path -ErrorAction Stop
} catch {
throw "Failed reading configuration file '$Path': $($_.Exception.Message)"
}
if ($null -eq $config) {
return @{}
}
return $config
}
function Test-GchConfigKey {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Config,
[Parameter(Mandatory)][string]$Key
)
if ($Config -is [hashtable]) {
return $Config.ContainsKey($Key)
}
return ($Config.PSObject.Properties[$Key] -ne $null)
}
function Get-GchConfigValue {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Config,
[Parameter(Mandatory)][string]$Key
)
if ($Config -is [hashtable]) {
return $Config[$Key]
}
return $Config.$Key
}
function Test-GchFalsyValue {
[CmdletBinding()]
param([AllowNull()]$Value)
if ($null -eq $Value) { return $true }
if ($Value -is [bool]) { return (-not $Value) }
if ($Value -is [int]) { return ($Value -eq 0) }
if ($Value -is [string]) {
$text = $Value.Trim()
if ([string]::IsNullOrWhiteSpace($text)) { return $true }
return ($text -in @('0', 'false', 'no', 'off'))
}
return (-not [bool]$Value)
}
function Resolve-GchConfiguredRepoUrl {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$RepoUrl)
$value = $RepoUrl.Trim()
$uri = $null
if (([string]::IsNullOrWhiteSpace($value)) -or (-not [System.Uri]::TryCreate($value, [System.UriKind]::Absolute, [ref]$uri))) {
throw "Invalid RepoUrl value in gch.psd1: '$RepoUrl'. Use a GitHub repository URL such as https://github.com/owner/repo."
}
if (($uri.Scheme -notin @('http', 'https')) -or ($uri.Host -ine 'github.com')) {
throw "Invalid RepoUrl value in gch.psd1: '$RepoUrl'. Use a GitHub repository URL such as https://github.com/owner/repo."
}
$parts = @($uri.AbsolutePath.Trim('/') -split '/')
if (($parts.Count -lt 2) -or [string]::IsNullOrWhiteSpace($parts[0]) -or [string]::IsNullOrWhiteSpace($parts[1])) {
throw "Invalid RepoUrl value in gch.psd1: '$RepoUrl'. Use a GitHub repository URL such as https://github.com/owner/repo."
}
$normalizedPath = ('{0}/{1}' -f $parts[0], (($parts[1] -replace '\.git$', '')))
return ('{0}://github.com/{1}' -f $uri.Scheme.ToLowerInvariant(), $normalizedPath)
}
function Resolve-GchConfiguredNonNegativeInteger {
[CmdletBinding()]
param(
[Parameter(Mandatory)]$Value,
[Parameter(Mandatory)][string]$Key
)
$text = ([string]$Value).Trim()
$number = 0
if (([string]::IsNullOrWhiteSpace($text)) -or (-not [int]::TryParse($text, [ref]$number)) -or ($number -lt 0)) {
throw "Invalid $Key value in gch.psd1: '$Value'. Use an integer greater than or equal to 0."
}
return $number
}
function Get-DiskFormatStateText {
[CmdletBinding()]
param(
[Parameter(Mandatory)][int]$CurrentDiskFormat,
[Parameter(Mandatory)][int]$LatestCompatibleCodeVersion
)
@"
@{
# This is the major version of the last code release that changed the On-Disk Format
CurrentDiskFormat = $CurrentDiskFormat
# This is the major version of the latest code that works fine with the above On-Disk Format
LatestCompatibleCodeVersion = $LatestCompatibleCodeVersion
}
"@
}
function Read-DiskFormatState {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
return @{
CurrentDiskFormat = 4
LatestCompatibleCodeVersion = 4
}
}
try {
$state = Import-PowerShellDataFile -LiteralPath $Path -ErrorAction Stop
} catch {
throw "Failed reading disk format state file '$Path': $($_.Exception.Message)"
}
if ($null -eq $state) {
throw "Disk format state file '$Path' did not contain a PowerShell data hash."
}
$current = Resolve-GchConfiguredNonNegativeInteger -Value $state.CurrentDiskFormat -Key 'CurrentDiskFormat'
$latestCompatible = Resolve-GchConfiguredNonNegativeInteger -Value $state.LatestCompatibleCodeVersion -Key 'LatestCompatibleCodeVersion'
return @{
CurrentDiskFormat = $current
LatestCompatibleCodeVersion = $latestCompatible
}
}
function Write-DiskFormatState {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][int]$CurrentDiskFormat,
[Parameter(Mandatory)][int]$LatestCompatibleCodeVersion
)
$parentDir = Split-Path -Parent $Path
if (-not [string]::IsNullOrWhiteSpace($parentDir) -and (-not (Test-Path -LiteralPath $parentDir -PathType Container))) {
$null = New-Item -ItemType Directory -Path $parentDir -Force
}
$text = Get-DiskFormatStateText -CurrentDiskFormat $CurrentDiskFormat -LatestCompatibleCodeVersion $LatestCompatibleCodeVersion
Set-Content -LiteralPath $Path -Value $text -Encoding UTF8
}
function Get-GetComputerHealthMajorVersion {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$Version)
$match = [regex]::Match($Version.Trim(), '^(?:v)?(?<Major>\d+)\.\d+\.\d+$', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if (-not $match.Success) {
throw "Invalid GetComputerHealth version '$Version'. Use semantic version format X.Y.Z."
}
return [int]$match.Groups['Major'].Value
}
function ConvertTo-DiskFormatManifestList {
[CmdletBinding()]
param([AllowNull()][string]$Value)
$items = @()
if ([string]::IsNullOrWhiteSpace($Value)) {
return $items
}
foreach ($item in ($Value -split ',')) {
$trimmed = $item.Trim()
if (-not [string]::IsNullOrWhiteSpace($trimmed)) {
$items += $trimmed
}
}
return $items
}
function Read-DiskFormatMigrationManifest {
[CmdletBinding()]
param([Parameter(Mandatory)][string]$ScriptPath)
$text = Get-Content -LiteralPath $ScriptPath -Raw -ErrorAction Stop
$manifestMatch = [regex]::Match($text, '(?is)\.MANIFEST\s*(?<Body>.*?)(?:\r?\n\s*\.[A-Z][A-Z0-9_-]*|\r?\n\s*#>)')
if (-not $manifestMatch.Success) {
throw "Migration script '$ScriptPath' is missing a .MANIFEST block."
}
$modifiedTopFolders = @()
$newTopFolders = @()
$lines = $manifestMatch.Groups['Body'].Value -split "`r?`n"
foreach ($line in $lines) {
$cleanLine = ([string]$line).Trim()
if ([string]::IsNullOrWhiteSpace($cleanLine) -or $cleanLine.StartsWith('#')) {
continue
}
$keyValueMatch = [regex]::Match($cleanLine, '^(?<Key>[A-Za-z][A-Za-z0-9_]*)\s*=\s*(?<Value>.*)$')
if (-not $keyValueMatch.Success) {
continue
}
$key = $keyValueMatch.Groups['Key'].Value
$value = $keyValueMatch.Groups['Value'].Value
if ($key -ieq 'ModifiedTopFolders') {
$modifiedTopFolders = ConvertTo-DiskFormatManifestList -Value $value
} elseif ($key -ieq 'NewTopFolders') {
$newTopFolders = ConvertTo-DiskFormatManifestList -Value $value
}
}
return @{
ModifiedTopFolders = @($modifiedTopFolders)
NewTopFolders = @($newTopFolders)
}
}
function Get-DiskFormatMigrationScripts {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$MigrationDir,
[Parameter(Mandatory)][int]$SourceDiskFormat,
[Parameter(Mandatory)][int]$TargetCodeVersion
)
if (-not (Test-Path -LiteralPath $MigrationDir -PathType Container)) {
return @()
}
$results = @()
$files = @(Get-ChildItem -LiteralPath $MigrationDir -File -Filter 'migrate-to-version-*.ps1' -ErrorAction Stop)
foreach ($file in $files) {
$match = [regex]::Match($file.Name, '^migrate-to-version-(?<Version>\d+)\.ps1$', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
if (-not $match.Success) {
continue
}
$migrationVersion = [int]$match.Groups['Version'].Value
if (($migrationVersion -gt $SourceDiskFormat) -and ($migrationVersion -le $TargetCodeVersion)) {
$results += [pscustomobject]@{
Version = $migrationVersion
Path = $file.FullName
}
}
}
return @($results | Sort-Object -Property Version)
}
function Remove-OldDiskFormatMigrationBackups {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RootDir,
[int]$RetentionDays = 7
)
try {
$cutoff = (Get-Date).AddDays(-1 * $RetentionDays)
$oldBackups = @()
$backupCandidates = @(Get-ChildItem -LiteralPath $RootDir -Directory -Recurse -ErrorAction Stop)
foreach ($candidate in $backupCandidates) {
if (($candidate.Name -match '^\d+-to-\d+\.bak$') -and ($candidate.LastWriteTime -lt $cutoff)) {
$oldBackups += $candidate
}
}
foreach ($backup in $oldBackups) {
Write-Verbose "Deleting old disk format migration backup '$($backup.FullName)'"
Remove-Item -LiteralPath $backup.FullName -Recurse -Force -ErrorAction Stop
}
} catch {
Write-Warning ("Failed pruning old disk format migration backups in {0}: {1}" -f $RootDir, $_.Exception.Message)
}
}
function Backup-DiskFormatMigrationFolders {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RootDir,
[Parameter(Mandatory)][string[]]$TopFolders,
[Parameter(Mandatory)][int]$FromVersion,
[Parameter(Mandatory)][int]$ToVersion
)
$backups = @()
foreach ($topFolder in $TopFolders) {
if ([string]::IsNullOrWhiteSpace($topFolder)) {
continue
}
if ($topFolder.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -ge 0) {
throw "Invalid top folder name in migration manifest: '$topFolder'"
}
$sourcePath = Join-Path $RootDir $topFolder
$backupPath = Join-Path $sourcePath ('{0}-to-{1}.bak' -f $FromVersion, $ToVersion)
$backupLeafName = Split-Path -Leaf $backupPath
if (Test-Path -LiteralPath $backupPath) {
Write-Verbose "Deleting existing disk format migration backup '$backupPath'"
Remove-Item -LiteralPath $backupPath -Recurse -Force -ErrorAction Stop
}
if (Test-Path -LiteralPath $sourcePath -PathType Container) {
Write-Verbose "Creating disk format migration backup '$backupPath' from '$sourcePath'"
New-Item -ItemType Directory -Path $backupPath -Force -ErrorAction Stop | Out-Null
$sourceChildren = @(Get-ChildItem -LiteralPath $sourcePath -Force -ErrorAction Stop)
foreach ($child in $sourceChildren) {
if ($child.Name -ieq $backupLeafName) {
continue
}
Copy-Item -LiteralPath $child.FullName -Destination $backupPath -Recurse -Force -ErrorAction Stop
}
Write-UpdateEvent "Created disk format migration backup '$backupPath'"
$backups += [pscustomobject]@{
TopFolder = $topFolder
SourcePath = $sourcePath
BackupPath = $backupPath
HadSource = $true
}
} else {
Write-Verbose "Top folder '$sourcePath' does not exist; no migration backup needed"
$backups += [pscustomobject]@{
TopFolder = $topFolder
SourcePath = $sourcePath
BackupPath = $backupPath
HadSource = $false
}
}
}
return @($backups)
}
function Restore-DiskFormatMigrationFolders {
[CmdletBinding()]
param([Parameter(Mandatory)]$Backups)
foreach ($backup in @($Backups)) {
if ($backup.HadSource) {
if (-not (Test-Path -LiteralPath $backup.BackupPath -PathType Container)) {
throw "Cannot restore disk format migration backup because '$($backup.BackupPath)' no longer exists."
}
if (-not (Test-Path -LiteralPath $backup.SourcePath -PathType Container)) {
New-Item -ItemType Directory -Path $backup.SourcePath -Force -ErrorAction Stop | Out-Null
}
$backupLeafName = Split-Path -Leaf $backup.BackupPath
$sourceChildren = @(Get-ChildItem -LiteralPath $backup.SourcePath -Force -ErrorAction Stop)
foreach ($child in $sourceChildren) {
if ($child.Name -ieq $backupLeafName) {
continue
}
Write-Verbose "Removing modified path '$($child.FullName)' before restore"
Remove-Item -LiteralPath $child.FullName -Recurse -Force -ErrorAction Stop
}
Write-Verbose "Restoring disk format migration backup '$($backup.BackupPath)' to '$($backup.SourcePath)'"
$backupChildren = @(Get-ChildItem -LiteralPath $backup.BackupPath -Force -ErrorAction Stop)
foreach ($child in $backupChildren) {
Copy-Item -LiteralPath $child.FullName -Destination $backup.SourcePath -Recurse -Force -ErrorAction Stop
}
} elseif (Test-Path -LiteralPath $backup.SourcePath) {
Write-Verbose "Deleting folder '$($backup.SourcePath)' because it did not exist before the failed migration"
Remove-Item -LiteralPath $backup.SourcePath -Recurse -Force -ErrorAction Stop
}
}
}
function Remove-DiskFormatMigrationNewFolders {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RootDir,
[Parameter(Mandatory)][string[]]$TopFolders,
[string[]]$ExistingTopFolders = @()
)
$existing = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
foreach ($topFolder in $ExistingTopFolders) {
if (-not [string]::IsNullOrWhiteSpace($topFolder)) {
$null = $existing.Add($topFolder)
}
}
foreach ($topFolder in $TopFolders) {
if ([string]::IsNullOrWhiteSpace($topFolder)) {
continue
}
if ($existing.Contains($topFolder)) {
Write-Verbose "Leaving existing folder '$topFolder' in place after failed migration"
continue
}
$path = Join-Path $RootDir $topFolder
if (Test-Path -LiteralPath $path) {
Write-Verbose "Deleting new folder introduced by failed migration: '$path'"
Remove-Item -LiteralPath $path -Recurse -Force -ErrorAction Stop
}
}
}
function Invoke-DiskFormatMigrationScript {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$ScriptPath,
[Parameter(Mandatory)][string]$WorkingDirectory
)
$powerShellExe = Join-Path $PSHOME 'powershell.exe'
if (-not (Test-Path -LiteralPath $powerShellExe -PathType Leaf)) {
$powerShellExe = 'powershell.exe'
}
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = $powerShellExe
$startInfo.Arguments = ('-NoProfile -ExecutionPolicy Bypass -File "{0}"' -f ($ScriptPath -replace '"', '\"'))
$startInfo.UseShellExecute = $false
$startInfo.RedirectStandardOutput = $true
$startInfo.RedirectStandardError = $true
$startInfo.CreateNoWindow = $true
$startInfo.WorkingDirectory = $WorkingDirectory
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$null = $process.Start()
$stdout = $process.StandardOutput.ReadToEnd()
$stderr = $process.StandardError.ReadToEnd()
$process.WaitForExit()
if (-not [string]::IsNullOrWhiteSpace($stdout)) {
Write-Host $stdout.TrimEnd()
}
if (-not [string]::IsNullOrWhiteSpace($stderr)) {
Write-Warning $stderr.TrimEnd()
}
$stdoutLines = @()
if (-not [string]::IsNullOrWhiteSpace($stdout)) {
$stdoutLines = @($stdout -split "`r?`n")
}
$lastStdoutLine = ''
for ($i = $stdoutLines.Count - 1; $i -ge 0; $i--) {
$candidate = ([string]$stdoutLines[$i]).Trim()
if (-not [string]::IsNullOrWhiteSpace($candidate)) {
$lastStdoutLine = $candidate
break
}
}
$updaterPath = $null
if ($lastStdoutLine -match '^PATH_TO_UPDATER=(?<Path>.+)$') {
$updaterPath = $matches['Path']
}
return [pscustomobject]@{
ExitCode = [int]$process.ExitCode
LastStdoutLine = $lastStdoutLine
UpdaterPath = $updaterPath
}
}
function Invoke-DiskFormatMigrations {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RootDir,
[Parameter(Mandatory)][string]$ReleaseRoot,
[Parameter(Mandatory)][string]$TargetCodeVersion
)
$targetCodeMajor = Get-GetComputerHealthMajorVersion -Version $TargetCodeVersion
$dataDir = Join-Path $RootDir 'data'
$statePath = Join-Path $dataDir 'disk-format.psd1'
$state = Read-DiskFormatState -Path $statePath
$sourceDiskFormat = [int]$state.CurrentDiskFormat
Write-UpdateEvent "Detected source disk format: $sourceDiskFormat"
Write-UpdateEvent "Target code major version: $targetCodeMajor"
Write-Verbose "Detected source disk format: $sourceDiskFormat"
Write-Verbose "Target code major version: $targetCodeMajor"
if ($targetCodeMajor -lt $sourceDiskFormat) {
throw "Format downgrade is not supported. Source disk format is $sourceDiskFormat but target code major version is $targetCodeMajor."
}
$mutex = New-Object System.Threading.Mutex($false, 'Global\GetComputerHealth-DiskFormatMigration')
$hasMutex = $false
try {
try {
$hasMutex = $mutex.WaitOne([TimeSpan]::FromSeconds(60))
} catch [System.Threading.AbandonedMutexException] {
$hasMutex = $true
Write-Warning 'Recovered an abandoned disk format migration mutex.'
}
if (-not $hasMutex) {
throw 'Another GetComputerHealth disk format migration is already running.'
}
Remove-OldDiskFormatMigrationBackups -RootDir $RootDir -RetentionDays 7
$migrationDir = Join-Path $ReleaseRoot 'disk-format-migrations'
$migrations = @(Get-DiskFormatMigrationScripts -MigrationDir $migrationDir -SourceDiskFormat $sourceDiskFormat -TargetCodeVersion $targetCodeMajor)
$currentDiskFormat = $sourceDiskFormat
$lastUpdaterPath = $null
if ($migrations.Count -eq 0) {
Write-Verbose "No disk format migration scripts found for versions greater than $sourceDiskFormat and less than or equal to $targetCodeMajor"
Write-UpdateEvent "No disk format migration is needed."
if ([int]$state.LatestCompatibleCodeVersion -ne $targetCodeMajor) {
Write-DiskFormatState -Path $statePath -CurrentDiskFormat $currentDiskFormat -LatestCompatibleCodeVersion $targetCodeMajor
Write-UpdateEvent "Persisted disk format: CurrentDiskFormat=$currentDiskFormat LatestCompatibleCodeVersion=$targetCodeMajor"
}
return [pscustomobject]@{
CurrentDiskFormat = $currentDiskFormat
LatestCompatibleCodeVersion = $targetCodeMajor
UpdaterPath = $null
RanMigrations = $false
}
}
foreach ($migration in $migrations) {
$manifest = Read-DiskFormatMigrationManifest -ScriptPath $migration.Path
$modifiedTopFolders = @($manifest.ModifiedTopFolders)
$newTopFolders = @($manifest.NewTopFolders)
Write-UpdateEvent ("Running disk format migration {0} from '{1}'" -f $migration.Version, $migration.Path)
$backups = @()
$existingNewTopFolders = @()
foreach ($topFolder in $newTopFolders) {
if ([string]::IsNullOrWhiteSpace($topFolder)) {
continue
}
if (Test-Path -LiteralPath (Join-Path $RootDir $topFolder)) {
$existingNewTopFolders += $topFolder
}
}
try {
$backups = @(Backup-DiskFormatMigrationFolders -RootDir $RootDir -TopFolders $modifiedTopFolders -FromVersion $currentDiskFormat -ToVersion $migration.Version)
$result = Invoke-DiskFormatMigrationScript -ScriptPath $migration.Path -WorkingDirectory $RootDir
if ($result.ExitCode -eq 0) {
if ([string]::IsNullOrWhiteSpace($result.UpdaterPath)) {
throw "Migration '$($migration.Path)' succeeded but did not emit PATH_TO_UPDATER as the last stdout line."
}
$lastUpdaterPath = $result.UpdaterPath
$currentDiskFormat = [int]$migration.Version
} elseif (($result.ExitCode -eq 1) -and ($result.LastStdoutLine -eq 'No migration is needed')) {
Write-Verbose "Migration '$($migration.Path)' reported that no action was needed"
$currentDiskFormat = [int]$migration.Version
} else {
throw "Migration '$($migration.Path)' failed with exit code $($result.ExitCode)."
}
} catch {
Write-Warning ("Disk format migration {0} failed; attempting restore: {1}" -f $migration.Version, $_.Exception.Message)
Restore-DiskFormatMigrationFolders -Backups $backups
Remove-DiskFormatMigrationNewFolders -RootDir $RootDir -TopFolders $newTopFolders -ExistingTopFolders $existingNewTopFolders
throw
}
}
Write-DiskFormatState -Path $statePath -CurrentDiskFormat $currentDiskFormat -LatestCompatibleCodeVersion $targetCodeMajor
Write-UpdateEvent "Persisted disk format: CurrentDiskFormat=$currentDiskFormat LatestCompatibleCodeVersion=$targetCodeMajor"
return [pscustomobject]@{
CurrentDiskFormat = $currentDiskFormat
LatestCompatibleCodeVersion = $targetCodeMajor
UpdaterPath = $lastUpdaterPath
RanMigrations = $true
}
} finally {
if ($hasMutex) {
$mutex.ReleaseMutex()
}
$mutex.Dispose()
}
}
function Start-UpdateTranscript {
<#
.SYNOPSIS
Starts transcript logging for the updater when possible.
#>
[CmdletBinding()]
param()
try {
$tempRoot = $env:TEMP
if ([string]::IsNullOrWhiteSpace($tempRoot)) {
$tempRoot = [System.IO.Path]::GetTempPath()
}
$script:UpdateTranscriptTempPath = Join-Path $tempRoot ("Update-GetHealthCode-{0}.transcript.log" -f [guid]::NewGuid().ToString())
Start-Transcript -Path $script:UpdateTranscriptTempPath -Force -ErrorAction Stop | Out-Null
$script:UpdateTranscriptStarted = $true
} catch {
$script:UpdateTranscriptStarted = $false
$script:UpdateTranscriptTempPath = $null
Write-Warning ("Failed to start transcript log in temp storage: {0}" -f $_.Exception.Message)
}
}
function Stop-UpdateTranscript {
<#
.SYNOPSIS
Stops transcript logging for the updater when it was started.
#>
[CmdletBinding()]
param()
if (-not $script:UpdateTranscriptStarted) {
return
}
try {
Stop-Transcript | Out-Null
} catch {
Write-Warning ("Failed to stop transcript log at {0}: {1}" -f $script:UPDATE_LOG_PATH, $_.Exception.Message)
} finally {
$script:UpdateTranscriptStarted = $false
}
}
function Finalize-UpdateTranscript {
<#
.SYNOPSIS
Moves a completed updater transcript from temp storage into the log folder.
#>
[CmdletBinding()]
param()
if ([string]::IsNullOrWhiteSpace($script:UpdateTranscriptTempPath)) {
return
}
try {
if (-not (Test-Path -LiteralPath $script:UpdateTranscriptTempPath -PathType Leaf)) {
return
}
if (-not (Test-Path -LiteralPath $LOG_DIR -PathType Container)) {
$null = New-Item -ItemType Directory -Path $LOG_DIR -Force
}
$timestampText = $script:UpdateTranscriptTimestamp.ToString('yyyy-MM-dd_HH.mm.ss')
$script:UpdateTranscriptFinalPath = Join-Path $LOG_DIR ("Update-GetHealthCode-{0}.log" -f $timestampText)
Move-Item -LiteralPath $script:UpdateTranscriptTempPath -Destination $script:UpdateTranscriptFinalPath -Force -ErrorAction Stop
} catch {
Write-Warning ("Failed to finalize transcript log from {0}: {1}" -f $script:UpdateTranscriptTempPath, $_.Exception.Message)
} finally {
$script:UpdateTranscriptTempPath = $null
}
}
function Ensure-PSModuleInstalled {
<#
.SYNOPSIS
Ensures a PowerShell module is installed locally; installs it if missing.
.DESCRIPTION
If installation fails due to PSGallery not being registered, registers
PSGallery, marks it Trusted, and retries the installation once.
.OUTPUTS
None.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$Name,
[string]$Scope = 'AllUsers'
)
Write-Verbose "Checking whether PowerShell module '$Name' is already installed"
if (Get-Module -ListAvailable -Name $Name) {
Write-Verbose "Module '$Name' is already installed"
return
}
Write-Verbose "Ensuring NuGet package provider is available for PowerShellGet"
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope $Scope -ErrorAction Stop | Out-Null
Import-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction Stop | Out-Null
try {
Write-Verbose "Installing PowerShell module '$Name' with scope '$Scope'"
Install-Module -Name $Name -Scope $Scope -Force -Confirm:$false -ErrorAction Stop
Write-Verbose "Successfully installed PowerShell module '$Name'"
} catch {
if ($_.Exception.Message -like "*No repository with the Name 'PSGallery'*") {
Write-Warning "Registering PSGallery"
Write-Verbose "Registering default PSRepository because PSGallery was missing"
Register-PSRepository -Default -ErrorAction Stop
Write-Verbose "Marking PSGallery as Trusted"
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted -ErrorAction Stop
Write-Verbose "Retrying installation of PowerShell module '$Name'"
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope $Scope -ErrorAction Stop | Out-Null
Import-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction Stop | Out-Null
Install-Module -Name $Name -Scope $Scope -Force -Confirm:$false -ErrorAction Stop
Write-Verbose "Successfully installed PowerShell module '$Name' after registering PSGallery"
} else {
throw
}
}
}
function New-RandomTempDirectoryPath {
<#
.SYNOPSIS
Returns an unused "$TempRoot\<Name>.<N>" path where N is between 0 and 9999.
.OUTPUTS
System.String. A currently unused temporary directory path.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$TempRoot,
[Parameter(Mandatory)][string]$Name
)
for ($attempt = 0; $attempt -lt 100; $attempt++) {
$suffix = Get-Random -Minimum 0 -Maximum 10000
$candidate = Join-Path $TempRoot ("{0}.{1}" -f $Name, $suffix)
if (-not (Test-Path -LiteralPath $candidate -ErrorAction SilentlyContinue)) {
return $candidate
}
}
throw "Could not find an available temporary directory matching '$Name.<N>' under '$TempRoot' after 100 attempts."
}
function New-EmptyTempDirectory {
<#
.SYNOPSIS
Creates a reusable temporary directory and returns its full path.
.OUTPUTS
System.String. The full path of the created directory under $env:TEMP.
#>
[CmdletBinding()]
param([string]$Name)
$tempRoot = $env:TEMP
if ([string]::IsNullOrWhiteSpace($tempRoot)) {
$tempRoot = [System.IO.Path]::GetTempPath()
}
$tmdDir = Join-Path $tempRoot $Name
Write-Verbose "Preparing temporary directory '$tmdDir'"
if (Test-Path -LiteralPath $tmdDir) {
if (Test-Path -LiteralPath $tmdDir -PathType Container) {
Write-Verbose "Temporary directory already exists; clearing its contents: '$tmdDir'"
try {
Get-ChildItem -LiteralPath $tmdDir -Recurse -Force -ErrorAction Stop |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
} catch {
Write-Warning ("Could not clear temporary directory '{0}': {1}" -f $tmdDir, $_.Exception.Message)
$tmdDir = New-RandomTempDirectoryPath -TempRoot $tempRoot -Name $Name
Write-Verbose "Using alternate temporary directory '$tmdDir'"
}
} else {
Write-Verbose "A file already exists at '$tmdDir'; generating a unique directory name"
$tmdDir = New-RandomTempDirectoryPath -TempRoot $tempRoot -Name $Name
Write-Verbose "Using alternate temporary directory '$tmdDir'"
}
}
$null = New-Item -ItemType Directory -Path $tmdDir -Force
Write-Verbose "Temporary directory ready: '$tmdDir'"
return $tmdDir
}
function Convert-GitHubRepoUrlToSlug {
<#
.SYNOPSIS
Converts a GitHub repo URL into "owner/repo" format.
#>
[CmdletBinding()]
param([Parameter(Mandatory)][string]$RepoUrl)
Write-Verbose "Converting repository URL to slug: '$RepoUrl'"
$slug = ($RepoUrl -replace '^https?://github\.com/','') -replace '\.git$',''
$slug = $slug.Trim('/')
if ([string]::IsNullOrWhiteSpace($slug)) {
throw "Invalid GitHub repository URL: $RepoUrl"
}
Write-Verbose "Repository slug resolved to '$slug'"
return $slug
}
function Convert-GetComputerHealthReleaseToMarker {
<#
.SYNOPSIS
Converts release metadata to a stable marker string.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RepositoryUrl,
[Parameter(Mandatory)]$Release
)
$slug = Convert-GitHubRepoUrlToSlug -RepoUrl $RepositoryUrl
$tag = [string]$Release.tag_name
if ([string]::IsNullOrWhiteSpace($tag)) { $tag = 'untagged' }
$id = [string]$Release.id
if ([string]::IsNullOrWhiteSpace($id)) { $id = 'noid' }
return ("{0}|{1}|{2}" -f $slug, $tag, $id)
}
function Get-GetComputerHealthVersionFromMarker {
<#
.SYNOPSIS
Extracts a comparable release version token from an installed/latest marker.
.DESCRIPTION
Returns values like 'v3.9.0' when the marker embeds a semantic-version tag,
or $null when no version-like token can be identified.
#>
[CmdletBinding()]
param([AllowNull()][string]$Marker)
if ([string]::IsNullOrWhiteSpace($Marker)) {
return $null
}
if ($Marker -match '(?i)\bv\d+\.\d+\.\d+\b') {
return $matches[0].ToLowerInvariant()
}
return $null
}
function ConvertTo-GetComputerHealthVersionToken {
<#
.SYNOPSIS