-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInstall-RemoteMSI.ps1
More file actions
2459 lines (2049 loc) · 94 KB
/
Install-RemoteMSI.ps1
File metadata and controls
2459 lines (2049 loc) · 94 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
Remotely installs an MSI/MSIX package on one or more remote Windows machines.
.DESCRIPTION
Supports single-machine and batch execution with:
- Domain credential validation before heavy processing
- Hostname sanitization
- Batch input file discovery (CSV/TXT)
- Five-state machine pre-validation (AD/DNS/reachability/WinRM)
- Throttled parallel installation batches
- File transfer retry policy (5s, 10s, 30s, 60s)
- Per-machine retry rounds after each batch (failed machines only)
- One aggregated log file per script run
- In-place success commenting in source machine file for reruns
#>
[CmdletBinding()]
param(
[switch]$NonInteractive,
[string]$RunLogPath
)
$ErrorActionPreference = 'Stop'
# ============================================================================
# CONFIGURATION
# ============================================================================
$ScriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
$LocalMSIPath = $ScriptDirectory
$RemoteTempPath = 'C:\Temp'
$LogDirectory = Join-Path -Path $ScriptDirectory -ChildPath 'Logs'
$MaxCredentialAttempts = 2
$TransferRetryDelays = @(5, 10, 30, 60)
$LogPath = $null
$RunId = Get-Date -Format 'yyyyMMdd_HHmmss'
$ScriptPath = if ($PSCommandPath) { $PSCommandPath } else { $MyInvocation.MyCommand.Path }
# ============================================================================
# LOGGING
# ============================================================================
function Initialize-RunLog {
if (-not (Test-Path -Path $LogDirectory)) {
New-Item -ItemType Directory -Path $LogDirectory -Force | Out-Null
}
if (-not [string]::IsNullOrWhiteSpace($RunLogPath)) {
$resolvedPath = $RunLogPath
$resolvedDirectory = Split-Path -Path $resolvedPath -Parent
if ($resolvedDirectory -and -not (Test-Path -Path $resolvedDirectory)) {
New-Item -ItemType Directory -Path $resolvedDirectory -Force | Out-Null
}
$script:LogPath = $resolvedPath
if (-not (Test-Path -Path $script:LogPath -PathType Leaf)) {
New-Item -Path $script:LogPath -ItemType File -Force | Out-Null
}
return
}
$script:LogPath = Join-Path -Path $LogDirectory -ChildPath "Deployment_$RunId.log"
New-Item -Path $script:LogPath -ItemType File -Force | Out-Null
}
function Write-Log {
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $false)]
[ValidateSet('INFO', 'SUCCESS', 'ERROR', 'WARNING')]
[string]$Level = 'INFO'
)
$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logMessage = "$timestamp [$Level] $Message"
$color = switch ($Level) {
'SUCCESS' { 'Green' }
'ERROR' { 'Red' }
'WARNING' { 'Yellow' }
default { 'Cyan' }
}
Write-Host $logMessage -ForegroundColor $color
if ($script:LogPath) {
Add-Content -Path $script:LogPath -Value $logMessage -Encoding UTF8
}
}
# ============================================================================
# INPUT / VALIDATION HELPERS
# ============================================================================
function Get-Confirmation {
param(
[Parameter(Mandatory = $true)]
[string]$Prompt
)
while ($true) {
$response = (Read-Host "$Prompt [Y/N]").Trim().ToUpperInvariant()
if ($response -in @('Y', 'YES')) { return $true }
if ($response -in @('N', 'NO')) { return $false }
Write-Log "Please enter Y or N." -Level WARNING
}
}
function ConvertTo-Hostname {
param(
[Parameter(Mandatory = $true)]
[string]$RawName
)
$trimmed = $RawName.Trim()
if ([string]::IsNullOrWhiteSpace($trimmed)) {
return $null
}
$cleaned = ($trimmed -replace '[^a-zA-Z0-9\-\._]', '')
if ([string]::IsNullOrWhiteSpace($cleaned)) {
return $null
}
return $cleaned
}
function Test-ComputerInAD {
param(
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
try {
if (Get-Command -Name Get-ADComputer -ErrorAction SilentlyContinue) {
$adComputer = Get-ADComputer -Identity $ComputerName -ErrorAction SilentlyContinue
if ($adComputer) {
return $true
}
return $false
}
Write-Log "ActiveDirectory module not available. Falling back to DNS validation for '$ComputerName'." -Level WARNING
$dnsResolve = Resolve-DnsName -Name $ComputerName -ErrorAction SilentlyContinue
return [bool]$dnsResolve
}
catch {
return $false
}
}
function Test-ComputerOnline {
param(
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
try {
$tcpAvailable = $false
try {
if (Get-Command -Name Test-NetConnection -ErrorAction SilentlyContinue) {
$tcpAvailable = [bool](Test-NetConnection -ComputerName $ComputerName -Port 5985 -InformationLevel Quiet -WarningAction SilentlyContinue -ErrorAction Stop)
}
else {
$tcpClient = New-Object System.Net.Sockets.TcpClient
try {
$connectResult = $tcpClient.BeginConnect($ComputerName, 5985, $null, $null)
$connectedInTime = $connectResult.AsyncWaitHandle.WaitOne(5000, $false)
if ($connectedInTime) {
$tcpAvailable = $true
}
}
finally {
try { [void]$tcpClient.EndConnect($connectResult) } catch { }
try {
if ($connectResult -and $connectResult.AsyncWaitHandle) {
$connectResult.AsyncWaitHandle.Close()
}
}
catch { }
if ($tcpClient) {
$tcpClient.Close()
}
}
}
}
catch {
# ignore and fallback to ICMP check
}
if ($tcpAvailable) {
return $true
}
$testConnection = Get-Command -Name Test-Connection -ErrorAction SilentlyContinue
if (-not $testConnection) {
return $false
}
$pingParams = @{
Quiet = $true
Count = 1
ErrorAction = 'Stop'
}
if ($testConnection.Parameters.ContainsKey('ComputerName')) {
$pingParams['ComputerName'] = $ComputerName
}
elseif ($testConnection.Parameters.ContainsKey('TargetName')) {
$pingParams['TargetName'] = $ComputerName
}
else {
return $false
}
if ($testConnection.Parameters.ContainsKey('TimeoutSeconds')) {
$pingParams['TimeoutSeconds'] = 5
}
elseif ($testConnection.Parameters.ContainsKey('TimeoutMilliseconds')) {
$pingParams['TimeoutMilliseconds'] = 5000
}
$ping = Test-Connection @pingParams
return [bool]$ping
}
catch {
return $false
}
}
function Resolve-ComputerIPAddresses {
param(
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
try {
$records = Resolve-DnsName -Name $ComputerName -ErrorAction Stop
$ips = @(
$records |
Where-Object { $_.IPAddress -and $_.Type -in @('A', 'AAAA') } |
Select-Object -ExpandProperty IPAddress -Unique
)
return @($ips)
}
catch {
return @()
}
}
function Test-ComputerWinRM {
param(
[Parameter(Mandatory = $true)]
[string]$ComputerName
)
try {
Test-WSMan -ComputerName $ComputerName -ErrorAction Stop | Out-Null
return $true
}
catch {
return $false
}
}
function Get-ValidatedSingleHostname {
while ($true) {
$rawHost = Read-Host "Enter the hostname of the target machine"
$hostName = ConvertTo-Hostname -RawName $rawHost
if (-not $hostName) {
Write-Log "Hostname is empty or contains only invalid characters." -Level WARNING
continue
}
if ($hostName -ne $rawHost.Trim()) {
Write-Log "Hostname sanitized to '$hostName'." -Level INFO
}
return $hostName
}
}
function Get-ExecutionMode {
Write-Host ("`n" + ('=' * 70))
Write-Host 'Remote MSI Installation Tool' -ForegroundColor Cyan
Write-Host ('=' * 70)
Write-Host '[1] Single Machine'
Write-Host '[2] Batch Deployment (CSV/TXT)'
while ($true) {
$selection = (Read-Host "Select mode [1-2]").Trim()
if ($selection -eq '1') { return 'Single' }
if ($selection -eq '2') { return 'Batch' }
Write-Log 'Invalid selection. Enter 1 or 2.' -Level WARNING
}
}
function Get-PowerShell7Details {
$details = [pscustomobject]@{
Available = $false
Path = $null
MajorVersion = 0
}
$candidatePaths = New-Object System.Collections.Generic.List[string]
$seen = @{}
function Add-CandidatePath {
param([string]$Path)
if ([string]::IsNullOrWhiteSpace($Path)) {
return
}
$normalized = $Path.Trim()
$key = $normalized.ToUpperInvariant()
if (-not $seen.ContainsKey($key)) {
$seen[$key] = $true
$candidatePaths.Add($normalized)
}
}
try {
$pwshCommand = Get-Command -Name 'pwsh' -ErrorAction SilentlyContinue
if ($pwshCommand -and $pwshCommand.Source) {
Add-CandidatePath -Path $pwshCommand.Source
}
}
catch {
# ignore and continue candidate discovery
}
if ($env:ProgramFiles) {
Add-CandidatePath -Path (Join-Path -Path ${env:ProgramFiles} -ChildPath 'PowerShell\7\pwsh.exe')
}
if ($env:ProgramW6432) {
Add-CandidatePath -Path (Join-Path -Path ${env:ProgramW6432} -ChildPath 'PowerShell\7\pwsh.exe')
}
if (${env:ProgramFiles(x86)}) {
Add-CandidatePath -Path (Join-Path -Path ${env:ProgramFiles(x86)} -ChildPath 'PowerShell\7\pwsh.exe')
}
foreach ($registryPath in @(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\pwsh.exe',
'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\pwsh.exe',
'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\pwsh.exe'
)) {
try {
if (-not (Test-Path -Path $registryPath)) {
continue
}
$regItem = Get-Item -Path $registryPath -ErrorAction SilentlyContinue
if ($regItem) {
$regPwshPath = $regItem.GetValue('')
if ($regPwshPath) {
Add-CandidatePath -Path $regPwshPath
}
}
}
catch {
# ignore registry read failures
}
}
foreach ($candidate in $candidatePaths) {
try {
if (-not (Test-Path -Path $candidate -PathType Leaf)) {
continue
}
$majorVersionOutput = & $candidate -NoProfile -NonInteractive -Command '$PSVersionTable.PSVersion.Major' 2>$null
$majorVersionText = ($majorVersionOutput | Select-Object -First 1).ToString().Trim()
$majorVersion = 0
if (-not [int]::TryParse($majorVersionText, [ref]$majorVersion)) {
continue
}
if ($majorVersion -gt $details.MajorVersion) {
$details.MajorVersion = $majorVersion
$details.Path = $candidate
}
if ($majorVersion -ge 7) {
$details.Available = $true
$details.Path = $candidate
$details.MajorVersion = $majorVersion
return $details
}
}
catch {
# ignore candidate execution failures
}
}
return $details
}
function Test-IsInteractiveSession {
if ($NonInteractive) {
return $false
}
return [Environment]::UserInteractive -and $Host.Name -ne 'ServerRemoteHost'
}
function Test-IsLocalAdministrator {
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
catch {
return $false
}
}
function Read-YesNoChoice {
param(
[Parameter(Mandatory = $true)]
[string]$Prompt,
[Parameter(Mandatory = $false)]
[bool]$DefaultYes = $true
)
$suffix = if ($DefaultYes) { '[Y/n]' } else { '[y/N]' }
while ($true) {
$response = (Read-Host "$Prompt $suffix").Trim().ToUpperInvariant()
if ([string]::IsNullOrWhiteSpace($response)) {
return $DefaultYes
}
if ($response -in @('Y', 'YES')) { return $true }
if ($response -in @('N', 'NO')) { return $false }
Write-Log 'Please enter Y or N.' -Level WARNING
}
}
function Install-PowerShell7ViaWindowsUpdate {
$result = [pscustomobject]@{
Success = $false
Message = ''
RebootRequired = $false
InstalledCount = 0
}
if (-not (Test-IsLocalAdministrator)) {
$result.Message = 'PowerShell 7 install via Windows Update requires running this script as local administrator.'
return $result
}
try {
$updateSession = New-Object -ComObject Microsoft.Update.Session
$searcher = $updateSession.CreateUpdateSearcher()
$searchResult = $searcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0")
$candidates = New-Object -ComObject Microsoft.Update.UpdateColl
foreach ($update in $searchResult.Updates) {
$title = [string]$update.Title
if ($title -match '(?i)PowerShell' -and $title -match '(?i)\b7(\.\d+)?\b') {
if (-not $update.EulaAccepted) {
$update.AcceptEula()
}
[void]$candidates.Add($update)
}
}
if ($candidates.Count -eq 0) {
$result.Message = 'No approved/applicable PowerShell 7 updates were found from the configured Windows Update service.'
return $result
}
$downloader = $updateSession.CreateUpdateDownloader()
$downloader.Updates = $candidates
$downloadResult = $downloader.Download()
if ($downloadResult.ResultCode -notin 2, 3) {
$result.Message = "PowerShell 7 update download did not succeed (ResultCode=$($downloadResult.ResultCode))."
return $result
}
$installer = $updateSession.CreateUpdateInstaller()
$installer.Updates = $candidates
$installResult = $installer.Install()
$installedCount = 0
for ($i = 0; $i -lt $candidates.Count; $i++) {
$updateResultCode = $installResult.GetUpdateResult($i).ResultCode
if ($updateResultCode -in 2, 3) {
$installedCount++
}
}
$result.InstalledCount = $installedCount
$result.RebootRequired = [bool]$installResult.RebootRequired
$result.Success = $installedCount -gt 0
if ($result.Success) {
$result.Message = "Installed $installedCount PowerShell update(s) through configured Windows Update service."
}
else {
$result.Message = "PowerShell update install returned no successful updates (ResultCode=$($installResult.ResultCode))."
}
return $result
}
catch {
$result.Message = "Windows Update install attempt failed: $($_.Exception.Message)"
return $result
}
}
function Invoke-PowerShell7Relaunch {
param(
[Parameter(Mandatory = $true)]
[string]$PwshPath
)
try {
if ([string]::IsNullOrWhiteSpace($PwshPath) -or -not (Test-Path -LiteralPath $PwshPath -PathType Leaf)) {
throw "PowerShell 7 executable path is invalid: '$PwshPath'"
}
if ([string]::IsNullOrWhiteSpace($ScriptPath) -or -not (Test-Path -LiteralPath $ScriptPath -PathType Leaf)) {
throw "Script path for relaunch is invalid: '$ScriptPath'"
}
$launchArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $ScriptPath)
if ($script:LogPath) {
$launchArgs += @('-RunLogPath', $script:LogPath)
}
if ($NonInteractive) {
$launchArgs += '-NonInteractive'
}
Write-Log "Launching PowerShell 7 process: '$PwshPath' (same console)." -Level INFO
$childProcess = Start-Process -FilePath $PwshPath -ArgumentList $launchArgs -WorkingDirectory $ScriptDirectory -NoNewWindow -PassThru -Wait -ErrorAction Stop
if ($null -eq $childProcess) {
throw 'PowerShell 7 process failed to start.'
}
Write-Log "PowerShell 7 process exited with code $($childProcess.ExitCode)." -Level INFO
if ($childProcess.ExitCode -ne 0) {
Write-Log 'PowerShell 7 run ended with non-zero exit code. Check the latest child run log in Logs\Deployment_*.log for the exact failure reason.' -Level WARNING
}
return [int]$childProcess.ExitCode
}
catch {
Write-Log "Failed to relaunch in PowerShell 7+: $($_.Exception.Message)" -Level ERROR
return $null
}
}
function Invoke-PowerShell7Bootstrap {
$currentMajor = $PSVersionTable.PSVersion.Major
$isInteractive = Test-IsInteractiveSession
Write-Log "Runtime host version detected: PowerShell $currentMajor." -Level INFO
if ($currentMajor -ge 7) {
Write-Log 'PowerShell 7+ host detected. Startup bootstrap check complete.' -Level INFO
return
}
$pwshDetails = Get-PowerShell7Details
if ($pwshDetails.Available) {
Write-Log "PowerShell 7+ is installed at '$($pwshDetails.Path)'." -Level INFO
if ($isInteractive) {
$relaunchNow = Read-YesNoChoice -Prompt 'Relaunch this script now in PowerShell 7+ for full parallel support?' -DefaultYes $true
if ($relaunchNow) {
Write-Log "Relaunching in PowerShell 7+ using '$($pwshDetails.Path)'..." -Level INFO
$childExitCode = Invoke-PowerShell7Relaunch -PwshPath $pwshDetails.Path
if ($null -eq $childExitCode) {
Write-Log 'Relaunch failed. Continuing in current host with sequential fallback behavior.' -Level WARNING
return
}
exit $childExitCode
}
Write-Log 'Operator declined relaunch. This run will continue and use sequential fallback if parallel is requested.' -Level WARNING
}
else {
Write-Log 'Non-interactive session detected. Skipping relaunch prompt and continuing in current host.' -Level WARNING
}
return
}
Write-Log 'PowerShell 7+ is not currently installed on this machine.' -Level WARNING
if (-not $isInteractive) {
Write-Log 'Non-interactive session detected. Skipping PowerShell install attempt and continuing with sequential fallback behavior.' -Level WARNING
return
}
$attemptInstall = Read-YesNoChoice -Prompt 'Attempt to install PowerShell 7+ now using configured Windows Update service (WSUS/Microsoft Update)?' -DefaultYes $true
if (-not $attemptInstall) {
Write-Log 'Operator skipped PowerShell 7 installation attempt. Continuing in current host.' -Level WARNING
return
}
Write-Log 'Attempting PowerShell 7 install through configured Windows Update service...' -Level INFO
$installResult = Install-PowerShell7ViaWindowsUpdate
if ($installResult.Success) {
Write-Log $installResult.Message -Level SUCCESS
if ($installResult.RebootRequired) {
Write-Log 'Windows Update reported a reboot requirement after install. Relaunch may fail until reboot is completed.' -Level WARNING
}
}
else {
Write-Log $installResult.Message -Level WARNING
}
$pwshAfterInstall = Get-PowerShell7Details
if (-not $pwshAfterInstall.Available) {
Write-Log 'PowerShell 7+ is still unavailable after install attempt. Continuing with sequential fallback behavior.' -Level WARNING
return
}
Write-Log "PowerShell 7+ is now available at '$($pwshAfterInstall.Path)'." -Level SUCCESS
$relaunchAfterInstall = Read-YesNoChoice -Prompt 'Relaunch this script now in PowerShell 7+?' -DefaultYes $true
if (-not $relaunchAfterInstall) {
Write-Log 'Operator declined relaunch after install. Continuing in current host.' -Level WARNING
return
}
Write-Log "Relaunching in PowerShell 7+ using '$($pwshAfterInstall.Path)'..." -Level INFO
$childExitCodeAfterInstall = Invoke-PowerShell7Relaunch -PwshPath $pwshAfterInstall.Path
if ($null -eq $childExitCodeAfterInstall) {
Write-Log 'Relaunch failed after install. Continuing in current host with sequential fallback behavior.' -Level WARNING
return
}
exit $childExitCodeAfterInstall
}
function Get-InstallerFiles {
if (-not (Test-Path -Path $LocalMSIPath -PathType Container)) {
return @()
}
return @(Get-ChildItem -Path $LocalMSIPath -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -in @('.msi', '.msix') })
}
function Test-InstallerFilesExist {
if (-not (Test-Path -Path $LocalMSIPath -PathType Container)) {
throw "Script directory does not exist: $LocalMSIPath"
}
$allInstallerFiles = Get-InstallerFiles
if ($allInstallerFiles.Count -eq 0) {
throw "No MSI or MSIX files found in $LocalMSIPath"
}
}
function Get-MSIFile {
$installerFiles = Get-InstallerFiles
if ($installerFiles.Count -eq 0) { return $null }
if ($installerFiles.Count -eq 1) {
Write-Log "Installer selected automatically: $($installerFiles[0].Name)" -Level SUCCESS
return $installerFiles[0]
}
Write-Log "Found $($installerFiles.Count) installer files. Select one:" -Level INFO
for ($i = 0; $i -lt $installerFiles.Count; $i++) {
Write-Host " [$($i + 1)] $($installerFiles[$i].Name)"
}
while ($true) {
$selection = (Read-Host "Enter installer number [1-$($installerFiles.Count)]").Trim()
$selectionNumber = 0
if ([int]::TryParse($selection, [ref]$selectionNumber) -and $selectionNumber -ge 1 -and $selectionNumber -le $installerFiles.Count) {
$selectedFile = $installerFiles[$selectionNumber - 1]
Write-Log "Installer selected: $($selectedFile.Name)" -Level SUCCESS
return $selectedFile
}
Write-Log 'Invalid selection.' -Level WARNING
}
}
# ============================================================================
# CREDENTIALS
# ============================================================================
function Request-Credentials {
param(
[string]$Message = 'Enter credentials'
)
Write-Host $Message -ForegroundColor Cyan
$user = Read-Host 'User'
if ([string]::IsNullOrWhiteSpace($user)) {
return $null
}
$pass = Read-Host 'Password' -AsSecureString
if ($null -eq $pass) {
return $null
}
return New-Object System.Management.Automation.PSCredential($user.Trim(), $pass)
}
function Test-RemoteAdmin {
param(
[Parameter(Mandatory = $true)]
[System.Management.Automation.Runspaces.PSSession]$Session
)
$isAdmin = Invoke-Command -Session $Session -ScriptBlock {
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
return [bool]$isAdmin
}
function Test-CurrentUserDomainAuth {
try {
$currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
if ($null -eq $currentIdentity -or [string]::IsNullOrWhiteSpace($currentIdentity.Name)) {
return $false
}
if (-not ($currentIdentity.Name.Contains('\'))) {
return $false
}
$rootDse = [ADSI]'LDAP://RootDSE'
$defaultNamingContext = [string]$rootDse.defaultNamingContext
return -not [string]::IsNullOrWhiteSpace($defaultNamingContext)
}
catch {
return $false
}
}
function Test-DomainCredential {
param(
[Parameter(Mandatory = $true)]
[pscredential]$Credential
)
Add-Type -AssemblyName System.DirectoryServices.AccountManagement -ErrorAction SilentlyContinue
$result = [pscustomobject]@{
IsValid = $false
Message = ''
}
try {
$userNameRaw = [string]$Credential.UserName
if ([string]::IsNullOrWhiteSpace($userNameRaw)) {
$result.Message = 'Username is empty.'
return $result
}
$userNameRaw = $userNameRaw.Trim()
$domainName = $null
$userNameForValidate = $userNameRaw
if ($userNameRaw -match '^(?<domain>[^\\]+)\\(?<user>.+)$') {
$domainName = $Matches['domain']
$userNameForValidate = $Matches['user']
}
elseif ($userNameRaw -match '^(?<user>[^@]+)@(?<domain>.+)$') {
$domainName = $Matches['domain']
$userNameForValidate = $Matches['user']
}
else {
if (-not [string]::IsNullOrWhiteSpace($env:USERDNSDOMAIN)) {
$domainName = $env:USERDNSDOMAIN
}
elseif (-not [string]::IsNullOrWhiteSpace($env:USERDOMAIN)) {
$domainName = $env:USERDOMAIN
}
}
if ([string]::IsNullOrWhiteSpace($domainName)) {
$result.Message = 'Could not determine domain for credential validation. Use DOMAIN\User or User@Domain.'
return $result
}
$securePtr = [IntPtr]::Zero
try {
$securePtr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
$plainPassword = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($securePtr)
$context = New-Object System.DirectoryServices.AccountManagement.PrincipalContext(
[System.DirectoryServices.AccountManagement.ContextType]::Domain,
$domainName
)
try {
$isValid = $context.ValidateCredentials(
$userNameForValidate,
$plainPassword,
[System.DirectoryServices.AccountManagement.ContextOptions]::Negotiate
)
$result.IsValid = [bool]$isValid
if ($result.IsValid) {
$result.Message = "Domain credential authentication succeeded for '$userNameRaw'."
}
else {
$result.Message = "Domain credential authentication failed for '$userNameRaw'."
}
}
finally {
if ($context) {
$context.Dispose()
}
}
}
finally {
if ($securePtr -ne [IntPtr]::Zero) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($securePtr)
}
}
}
catch {
$result.Message = "Domain credential validation error: $($_.Exception.Message)"
}
return $result
}
function Get-ValidatedCredentialForDomain {
Write-Log 'Validating credentials against domain services before deployment.' -Level INFO
if (Test-CurrentUserDomainAuth) {
Write-Log 'Current user domain authentication validated successfully.' -Level SUCCESS
return $null
}
Write-Log 'Current user domain authentication could not be validated. Prompting for explicit credentials.' -Level WARNING
$attempt = 0
while ($attempt -lt $MaxCredentialAttempts) {
$attempt++
$credential = Request-Credentials -Message "Enter domain administrator credentials (attempt $attempt of $MaxCredentialAttempts)"
if ($null -eq $credential) {
throw 'Credential entry cancelled.'
}
$validationResult = Test-DomainCredential -Credential $credential
if ($validationResult.IsValid) {
Write-Log $validationResult.Message -Level SUCCESS
return $credential
}
Write-Log $validationResult.Message -Level WARNING
}
throw "Failed to validate domain credentials after $MaxCredentialAttempts attempts."
}
function Get-EffectiveCredentialIdentity {
param(
[Parameter(Mandatory = $false)]
[pscredential]$Credential
)
if ($Credential -and -not [string]::IsNullOrWhiteSpace($Credential.UserName)) {
return $Credential.UserName
}
try {
$currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
if ($currentIdentity -and -not [string]::IsNullOrWhiteSpace($currentIdentity.Name)) {
return $currentIdentity.Name
}
}
catch {
# ignore and fallback
}
if (-not [string]::IsNullOrWhiteSpace($env:USERDOMAIN) -and -not [string]::IsNullOrWhiteSpace($env:USERNAME)) {
return "$($env:USERDOMAIN)\$($env:USERNAME)"
}
return 'UnknownIdentity'
}
function Get-CredentialAfterUserConfirmation {
param(
[Parameter(Mandatory = $false)]
[pscredential]$CurrentCredential
)
$effectiveIdentity = Get-EffectiveCredentialIdentity -Credential $CurrentCredential
Write-Log "Current account selected for remote execution: '$effectiveIdentity'." -Level INFO
if (-not (Test-IsInteractiveSession)) {
Write-Log 'Non-interactive session detected. Skipping credential switch prompt and continuing with selected account.' -Level WARNING
return $CurrentCredential
}
$useAlternate = Read-YesNoChoice -Prompt "Current account is '$effectiveIdentity'. Use alternate credentials for remote execution?" -DefaultYes $false
if (-not $useAlternate) {
Write-Log "Operator accepted current account '$effectiveIdentity' for execution." -Level INFO
return $CurrentCredential
}
$attempt = 0
while ($attempt -lt $MaxCredentialAttempts) {
$attempt++
$alternateCredential = Request-Credentials -Message "Enter alternate domain credentials (attempt $attempt of $MaxCredentialAttempts)"
if ($null -eq $alternateCredential) {
throw 'Credential entry cancelled.'
}
$validationResult = Test-DomainCredential -Credential $alternateCredential
if ($validationResult.IsValid) {
Write-Log $validationResult.Message -Level SUCCESS
Write-Log "Operator switched execution account to '$($alternateCredential.UserName)'." -Level INFO
return $alternateCredential
}
Write-Log $validationResult.Message -Level WARNING
}
throw "Failed to validate alternate domain credentials after $MaxCredentialAttempts attempts."
}
function Invoke-AuthorizationCanaryCheck {
param(
[Parameter(Mandatory = $true)]
[string[]]$ReadyMachines,
[Parameter(Mandatory = $false)]
[pscredential]$Credential,
[Parameter(Mandatory = $false)]
[int]$MaxCanaryMachines = 3
)
if ($ReadyMachines.Count -eq 0) {
return [pscustomobject]@{
Success = $false
TestedMachines = @()
FailedChecks = @('No ready machines available for authorization canary check.')
}
}
$canaryCount = [Math]::Min([Math]::Max($MaxCanaryMachines, 1), $ReadyMachines.Count)
$testedMachines = @($ReadyMachines | Select-Object -First $canaryCount)
Write-Log "Running authorization canary check on $canaryCount machine(s): $($testedMachines -join ', ')." -Level INFO
$failedChecks = New-Object System.Collections.Generic.List[string]
foreach ($machine in $testedMachines) {
$session = $null
try {
if ($Credential) {
$session = New-PSSession -ComputerName $machine -Credential $Credential -ErrorAction Stop
}
else {
$session = New-PSSession -ComputerName $machine -ErrorAction Stop
}
$isAdmin = Test-RemoteAdmin -Session $session
if (-not $isAdmin) {
$failedChecks.Add("${machine}: Connected, but account is not local administrator.")
Write-Log "[$machine] Canary authorization failed: account is not local administrator." -Level WARNING
continue
}
Write-Log "[$machine] Canary authorization succeeded (remote admin confirmed)." -Level SUCCESS
}
catch {
$failedChecks.Add("${machine}: $($_.Exception.Message)")
Write-Log "[$machine] Canary authorization failed: $($_.Exception.Message)" -Level WARNING
}
finally {
if ($session) {
Remove-PSSession -Session $session -ErrorAction SilentlyContinue
}
}
}
return [pscustomobject]@{
Success = $failedChecks.Count -eq 0
TestedMachines = $testedMachines
FailedChecks = @($failedChecks)
}