-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUpdate-TemurinJava.ps1
More file actions
2552 lines (2092 loc) · 111 KB
/
Update-TemurinJava.ps1
File metadata and controls
2552 lines (2092 loc) · 111 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
Manages Adoptium Eclipse Temurin OpenJDK/OpenJRE installations, checking for updates and installing new versions
.DESCRIPTION
This script identifies installed Adoptium Eclipse Temurin OpenJDK and OpenJRE installations,
checks GitHub releases for newer versions within the same major version, and performs silent updates.
It can also install new versions when specified. The script self-installs to ProgramData and creates
a scheduled task for daily update checks.
.PARAMETER Install
Switch parameter to enable installation mode for new Java versions
.PARAMETER Versions
Comma-separated list of major Java versions to install (e.g., "8,11,17,21")
.PARAMETER Arch
Architecture to install: "x64" or "x86"
.PARAMETER Type
Type of Java to install: "JRE" or "JDK" (defaults to "JRE")
.PARAMETER Force
Forces the script to copy itself even if it already exists in the target location
.PARAMETER SkipScheduledTask
Skips the creation of the scheduled task
.EXAMPLE
.\Update-TemurinJava.ps1
Checks for updates to existing Temurin installations
.EXAMPLE
.\Update-TemurinJava.ps1 -Install -Versions "8,17" -Arch "x64" -Type "JRE"
Installs JRE versions 8 and 17 for x64 architecture
.EXAMPLE
.\Update-TemurinJava.ps1 -Force
Forces reinstallation of the script and scheduled task
.NOTES
Author: Mark Newton
Version: 1.0
Created: 08/15/2025
#>
# ================================
# === PARAMS ===
# ================================
#region Parameters
[CmdletBinding(DefaultParameterSetName = 'Update')]
Param(
[Parameter(ParameterSetName = 'Install', Mandatory = $true)]
[Switch]$Install,
[Parameter(ParameterSetName = 'Install', Mandatory = $true)]
[ValidatePattern('^(\d+,)*\d+$')]
[String]$Versions,
[Parameter(ParameterSetName = 'Install', Mandatory = $true)]
[ValidateSet('x64', 'x86')]
[String]$Arch,
[Parameter(ParameterSetName = 'Install')]
[ValidateSet('JRE', 'JDK')]
[String]$Type = 'JRE',
[Parameter(ParameterSetName = 'Update')]
[Parameter(ParameterSetName = 'Install')]
[Switch]$Force,
[Parameter(ParameterSetName = 'Update')]
[Parameter(ParameterSetName = 'Install')]
[Switch]$SkipScheduledTask
)
#endregion
# ================================
# === CONFIG VARS (EDITABLE) ===
# ================================
#region Configuration Variables (Editable)
# Paths and directories
$Script:InstallPath = 'C:\ProgramData\Update-TemurinJava'
$Script:ScriptName = 'Update-TemurinJava.ps1'
$Script:TempDownloadPath = Join-Path $Script:InstallPath 'Installers'
$Script:LogPath = 'C:\ProgramData\Update-TemurinJava\Logs'
# Scheduled task configuration
$Script:ScheduledTaskName = 'UpdateTemurinJava'
$Script:ScheduledTaskDescription = 'Daily check for Adoptium Eclipse Temurin Java updates'
$Script:ScheduledTaskTime = '08:00:00'
# Update check configuration
$Script:MaxRetryAttempts = 5
$Script:InitialRetryDelaySeconds = 5
#endregion
# ================================
# === CONFIG VARS (DONT EDIT) ===
# ================================
#region Configuration Variables (Don't Edit)
# GitHub API endpoints for different Java versions
$Script:GitHubRepos = @{
'8' = 'https://api.github.com/repos/adoptium/temurin8-binaries/releases/latest'
'11' = 'https://api.github.com/repos/adoptium/temurin11-binaries/releases/latest'
'17' = 'https://api.github.com/repos/adoptium/temurin17-binaries/releases/latest'
'21' = 'https://api.github.com/repos/adoptium/temurin21-binaries/releases/latest'
}
# Architecture mapping for GitHub downloads
$Script:ArchMapping = @{
'x64' = 'x64_windows'
'x86' = 'x86-32_windows'
}
# Type mapping for GitHub downloads
$Script:TypeMapping = @{
'JRE' = 'jre'
'JDK' = 'jdk'
}
# Script execution context
$Script:LogFileName = 'Update-TemurinJava'
$Script:DefaultLogger = $null
$Script:ConsoleLogger = $null
$Script:Debug = $false
# Temporary file tracking for cleanup
$Script:MSIInstallers = [System.Collections.Generic.List[String]]::new()
#endregion
# ================================
# === LOGGING FUNCTIONS ===
# ================================
#region Logging Functions
Class Logger {
<#
.DESCRIPTION
Class that handles logging operations with multiple options including file rotation, encoding options, and console output
.EXAMPLE
# Create a new logger with default settings
$Logger = [Logger]::new("MyLog")
$Logger.Write("Hello World!")
# Create a logger with custom settings
$Logger = [Logger]::new("ApplicationLog", "C:\Logs", "WARNING")
$Logger.Write("This is a warning message")
# Create a logger with log rotation settings
$Logger = [Logger]::new()
$Logger.LogName = "RotatingLog"
$Logger.LogRotateOpt = "10M"
$Logger.LogZip = $True
$Logger.Write("This message will be in a log that rotates at 10MB")
#>
# Required properties
[string]$LogName
[string]$LogPath
[string]$LogLevel
# Optional configuration properties
[string]$DateTimeFormat
[bool]$NoLogInfo
[string]$Encoding
[bool]$LogRoll
[int]$LogRetry
[bool]$WriteConsole
[bool]$ConsoleOnly
[bool]$ConsoleInfo
[string]$LogRotateOpt
[bool]$LogZip
[int]$LogCountMax
# Hidden properties
hidden [string]$LogFile
# Default constructor
Logger() {
$This.InitializeDefaults()
}
# Constructor with basic parameters
Logger([string]$LogName) {
$This.InitializeDefaults()
$This.LogName = $LogName
}
# Constructor with extended parameters
Logger([string]$LogName, [string]$LogPath) {
$This.InitializeDefaults()
$This.LogName = $LogName
$This.LogPath = $LogPath
}
# Constructor with most common parameters
Logger([string]$LogName, [string]$LogPath, [string]$LogLevel) {
$This.InitializeDefaults()
$This.LogName = $LogName
$This.LogPath = $LogPath
$This.LogLevel = $LogLevel
}
# Initialize default values for all properties
hidden [void] InitializeDefaults() {
$This.LogName = "Debug"
$This.LogPath = "C:\Temp"
$This.LogLevel = "INFO"
$This.DateTimeFormat = 'yyyy-MM-dd HH:mm:ss'
$This.NoLogInfo = $False
$This.Encoding = 'Unicode'
$This.LogRoll = $False
$This.LogRetry = 2
$This.WriteConsole = $False
$This.ConsoleOnly = $False
$This.ConsoleInfo = $False
$This.LogRotateOpt = "1M"
$This.LogZip = $True
$This.LogCountMax = 5
# Set the log file path
$This.LogFile = "$($This.LogPath)\$($This.LogName).log"
}
# Update LogFile property when LogName or LogPath changes
[void] UpdateLogFile() {
$This.LogFile = "$($This.LogPath)\$($This.LogName).log"
}
# Main method to write to the log
[void] Write([string]$LogMsg) {
$This.Write($LogMsg, $This.LogLevel)
}
# Overload to specify log level
[void] Write([string]$LogMsg, [string]$LogLevel) {
# Update log file path if needed
$This.UpdateLogFile()
# If the Log directory doesn't exist, create it
If (!(Test-Path -Path $This.LogPath)) {
New-Item -ItemType "Directory" -Path $This.LogPath > $Null
}
# If the log file doesn't exist, create it
If (!(Test-Path -Path $This.LogFile)) {
Write-Output "[$([datetime]::Now.ToString($This.DateTimeFormat))][$LogLevel] Logging started" |
Out-File -FilePath $This.LogFile -Append -Encoding $This.Encoding
# Else check if the log needs to be rotated. If rotated, create a new log file.
} Else {
If ($This.LogRoll -and ($This.ConfirmLogRotation() -eq $True)) {
Write-Output "[$([datetime]::Now.ToString($This.DateTimeFormat))][$LogLevel] Log rotated... Logging started" |
Out-File -FilePath $This.LogFile -Append -Encoding $This.Encoding
}
}
# Write to the console
If ($This.WriteConsole) {
# Write timestamp and log level to the console
If ($This.ConsoleInfo) {
Write-Host "[$([datetime]::Now.ToString($This.DateTimeFormat))][$LogLevel] $LogMsg"
# Write just the log message to the console
} Else {
Write-Host "$LogMsg"
}
# Write to the console only and return to stop the function from writing to the log
If ($This.ConsoleOnly) {
Return
}
}
# Initialize variables for retrying if writing to log fails
$Saved = $False
$Retry = 0
# Retry writing to the log until we have success or have hit the maximum number of retries
Do {
# Increment retry by 1
$Retry++
# Try to write to the log file
Try {
# Write to the log without log info (timestamp and log level)
If ($This.NoLogInfo) {
Write-Output "$LogMsg" | Out-File -FilePath $This.LogFile -Append -Encoding $This.Encoding -ErrorAction Stop
# Write to the log with log info (timestamp and log level)
} Else {
Write-Output "[$([datetime]::Now.ToString($This.DateTimeFormat))][$LogLevel] $LogMsg" |
Out-File -FilePath $This.LogFile -Append -Encoding $This.Encoding -ErrorAction Stop
}
# Set saved variable to true. We successfully wrote to the log file.
$Saved = $True
} Catch {
If ($Saved -eq $False -and $Retry -eq $This.LogRetry) {
# Write the final error to the console. We were not able to write to the log file.
Write-Error "Logger couldn't write to the log File $($_.Exception.Message). Tried ($Retry/$($This.LogRetry)))"
Write-Error "Err Line: $($_.InvocationInfo.ScriptLineNumber) Err Name: $($_.Exception.GetType().FullName) Err Msg: $($_.Exception.Message)"
} Else {
# Write warning to the console and try again until we hit the maximum configured number of retries
Write-Warning "Logger couldn't write to the log File $($_.Exception.Message). Retrying... ($Retry/$($This.LogRetry))"
# Sleep for half a second
Start-Sleep -Milliseconds 500
}
}
} Until ($Saved -eq $True -or $Retry -ge $This.LogRetry)
}
# Convenience methods for different log levels
[void] WriteInfo([string]$LogMsg) {
$This.Write($LogMsg, "INFO")
}
[void] WriteWarning([string]$LogMsg) {
$This.Write($LogMsg, "WARNING")
}
[void] WriteError([string]$LogMsg) {
$This.Write($LogMsg, "ERROR")
}
[void] WriteDebug([string]$LogMsg) {
$This.Write($LogMsg, "DEBUG")
}
# Method to check if log rotation is needed
[bool] ConfirmLogRotation() {
<#
.DESCRIPTION
Determines if the log needs to be rotated per the parameters values. It supports rotating log files on disk and stored in a zip archive.
.EXAMPLE
$Logger = [Logger]::new("MyLog")
$Logger.LogRotateOpt = "10M"
$Logger.ConfirmLogRotation()
#>
# Initialize default return variable. If returned $True, will write a log rotate line to a new log file.
$LogRolled = $False
# Get the log name without the file extension
$This.LogName = "$([System.IO.Path]::GetFileNameWithoutExtension($This.LogFile))"
# Get the base path to the log file
$This.LogPath = Split-Path -Path $This.LogFile
# Initialize the zip archive path
$ZipPath = "$($This.LogPath)\$($This.LogName)-archive.zip"
# Initialize the TempLogPath variable to null.
$TempLogPath = $Null
# If the zip already exists, we set TempLogPath to a generated user temp folder path
# This will be used to extract the zip archive before rotating logs
If (Test-Path $ZipPath) {
$TempLogPath = "$([System.IO.Path]::GetTempPath())$($This.LogName).archive"
}
# Check If the LogRotateOpt matches the size pattern (e.g., 10M, 5G, 500K)
If ($This.LogRotateOpt -match '(\d+)([GMK])') {
$Unit = $matches[2]
# Calculate the log size and compare it to the LogRotateOpt size
If ($Unit -eq 'G') {
# Calculate size with GB
$RotateSize = [int]$matches[1] * 1GB
} ElseIf ($Unit -eq 'M') {
# Calculate size with MB
$RotateSize = [int]$matches[1] * 1MB
} ElseIf ($Unit -eq 'K') {
# Calculate size with KB
$RotateSize = [int]$matches[1] * 1KB
} Else {
Write-Warning "Incorrect log rotation parameter provided. Using default of 1MB."
$RotateSize = 1 * 1MB
}
$LogSize = ((Get-Item -Path $This.LogFile).Length)
If ($LogSize -gt $RotateSize) {
If ($This.LogZip) {
# Zip archive does not exist yet. Rotate existing logs and put them all inside of a zip archive
If (!(Test-Path $ZipPath)) {
# Get the list of current log files
$LogFiles = Get-ChildItem -Path $This.LogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") } |
Sort-Object BaseName
# Roll the log files
$LogRolled = $This.StartLogRoll($This.LogName, $This.LogPath, $LogFiles)
# Update the list of current log files after rotating
$LogFiles = Get-ChildItem -Path $This.LogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") -and ($_.Name -match '\.\d+') } |
Sort-Object BaseName
# Iterate over each log file and compress it into the archive and then delete it off the disk
ForEach ($File in $LogFiles) {
Compress-Archive -Path "$($This.LogPath)\$($File.Name)" -DestinationPath $ZipPath -Update
Remove-Item -Path "$($This.LogPath)\$($File.Name)"
}
Return $True
# Zip archive already exists. Lets extract and rotate some logs
} Else {
# Ensure the temp folder exists
If (-Not (Test-Path -Path $TempLogPath)) {
New-Item -Path $TempLogPath -ItemType Directory
}
# Unzip the File to the temp folder
Expand-Archive -Path $ZipPath -DestinationPath $TempLogPath -Force
# Get the LogFiles from the temp folder
$LogFiles = Get-ChildItem -Path $TempLogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") -and ($_.Name -match '\.\d+') } |
Sort-Object BaseName
# Roll the log files
$LogRolled = $This.StartLogRoll($This.LogName, $This.LogPath, $LogFiles)
Write-Host $TempLogPath
# Compress and overwrite the old log files inside the existing archive
Compress-Archive -Path "$TempLogPath\*" -DestinationPath $ZipPath -Update
# Remove the Files we extracted, we no longer need them
If (Test-Path $TempLogPath) {
Remove-Item -Path $TempLogPath -Recurse -Force
}
# Return True or False
Return $LogRolled
}
# Logs are not zipped, just roll em over
} Else {
$LogFiles = Get-ChildItem -Path $This.LogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") } |
Sort-Object BaseName
Write-Host $LogFiles
$LogRolled = $This.StartLogRoll($This.LogName, $This.LogPath, $LogFiles)
Return $LogRolled
}
}
# Check if LogRotateOpt matches the days pattern (e.g., 7, 30, 365)
} ElseIf ($This.LogRotateOpt -match '^\d+$') {
# Convert the string digit into an integer
$RotateDays = [int]$This.LogRotateOpt
# Get the file's last write time
$CreationTime = (Get-Item $This.LogFile).CreationTime
# Calculate the age of the file in days
$Age = ((Get-Date) - $CreationTime).Days
# If the age of the file is older than the configured number of days to rotate the log
If ($Age -gt $RotateDays) {
If ($This.LogZip) {
# Zip archive does not exist yet. Rotate existing logs and put them all inside of a zip archive
If (!(Test-Path $ZipPath)) {
# Get the list of current log files
$LogFiles = Get-ChildItem -Path $This.LogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") } |
Sort-Object BaseName
# Roll the log files
$LogRolled = $This.StartLogRoll($This.LogName, $This.LogPath, $LogFiles)
# Update the list of current log files after rotating
$LogFiles = Get-ChildItem -Path $This.LogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") -and ($_.Name -match '\.\d+') } |
Sort-Object BaseName
# Iterate over each log file and compress it into the archive and then delete it off the disk
ForEach ($File in $LogFiles) {
Compress-Archive -Path "$($This.LogPath)\$($File.Name)" -DestinationPath $ZipPath -Update
Remove-Item -Path "$($This.LogPath)\$($File.Name)"
}
Return $True
# Zip archive already exists. Lets extract and rotate some logs
} Else {
# Ensure the temp folder exists
If (-Not (Test-Path -Path $TempLogPath)) {
New-Item -Path $TempLogPath -ItemType Directory
}
# Unzip the File to the temp folder
Expand-Archive -Path $ZipPath -DestinationPath $TempLogPath -Force
# Get the LogFiles from the temp folder
$LogFiles = Get-ChildItem -Path $TempLogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") } |
Sort-Object BaseName
# Roll the log files
$LogRolled = $This.StartLogRoll($This.LogName, $This.LogPath, $LogFiles)
# Compress and overwrite the old log files inside the existing archive
Compress-Archive -Path "$TempLogPath\*" -DestinationPath $ZipPath -Update -Force
# Remove the Files we extracted, we no longer need them
If (Test-Path $TempLogPath) {
Remove-Item -Path $TempLogPath -Recurse -Force
}
# Return True or False
Return $LogRolled
}
# No zip archiving. Just roll us some logs on the disk.
} Else {
$LogFiles = Get-ChildItem -Path $This.LogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") } |
Sort-Object BaseName
$LogRolled = $This.StartLogRoll($This.LogName, $This.LogPath, $LogFiles)
Return $LogRolled
}
}
} Else {
Write-Error "Incorrect log rotation parameter provided. Logs will not be rotated!"
}
# Return false by default if no rotation was triggered
Return $False
}
# Method to perform log rotation
[bool] StartLogRoll([string]$LogName, [string]$LogPath, [object]$LogFiles) {
<#
.DESCRIPTION
Rolls the logs incrementing the number by 1 and deleting any older logs over the allowed maximum count of log files
.EXAMPLE
$Logger = [Logger]::new("MyLog")
$LogFiles = Get-ChildItem -Path $Logger.LogPath -File -Filter "*.log" | Where-Object { ($_.Name -like "$($Logger.LogName)*") -and ($_.Name -match '\.\d+') }
$Logger.StartLogRoll($Logger.LogName, $Logger.LogPath, $LogFiles)
#>
# Get the working log path from the $LogFiles object that was passed to the function.
# This may be a temp folder for zip archived logs.
$WorkingLogPath = $LogFiles[0].Directory
$LogFiles = Get-ChildItem -Path $WorkingLogPath -File -Filter "*.log" |
Where-Object { ($_.Name -like "$($This.LogName)*") -and ($_.Name -match '\.\d+') } |
Sort-Object BaseName
# Rotate multiple log files if 1 or more already exists
If ($LogFiles.Count -gt 0) {
# Iterate over the log files starting at the highest number and decrement down to 1
For ($i = $LogFiles.Count; $i -ge 0; $i--) {
# Get rotating log file that we are working on
$OperatingFile = $LogFiles | Where-Object {$_.Name -eq "$LogName.$i.log"}
# Check if we are over the maximum allowed rotating log files
If ($i -ge $This.LogCountMax) {
# Remove rotating logs that are over the maximum allowed
Remove-Item "$WorkingLogPath\$($OperatingFile.Name)" -Force -ErrorAction Stop
# If we have iterated down to zero, we are working with the base log file
} ElseIf ($i -eq 0) {
# Set the rotating log number
$OperatingNumber = 1
# Set the name of the new rotated log name
$NewFileName = "$LogName.$OperatingNumber.log"
If ($WorkingLogPath -eq $This.LogPath) {
# Rotate the base log
Rename-Item -Path "$WorkingLogPath\$LogName.log" -NewName $NewFileName
} Else {
Move-Item -Path "$LogPath\$LogName.log" -Destination "$WorkingLogPath\$LogName.1.log"
}
# Return true since all logs have been rotated
Return $True
# We are iterating through the rotated logs and renaming them as needed
} Else {
# Set the operating number to be +1 of the current increment
$OperatingNumber = $i + 1
# Set the name of the new rotated log name
$NewFileName = "$LogName.$OperatingNumber.log"
# Rotate the base log
Rename-Item -Path "$WorkingLogPath\$LogName.$i.log" -NewName $NewFileName -Force
}
}
# Rotate the base log file into its first rotating log file
} Else {
Move-Item -Path "$LogPath\$LogName.log" -Destination "$WorkingLogPath\$LogName.1.log"
# Return true since base log has been rotated
Return $True
}
# Return false since we didn't rotate any logs
Return $False
}
}
Function Initialize-Log {
<#
.DESCRIPTION
Initializes the logger class to be used by the write-log function. The class can be saved in a script variable as a default log
or it will be returned by the function which can be passed to Write-Log function to log into a specific log.
.PARAMETER LogName
Name of the log File that will be written to. It will have .log automatically appended as the File extension.
.PARAMETER LogPath
Path to the log File. Defaults to a Logs subfolder wherever the script is ran from.
.PARAMETER LogLevel
The default log level to be used if a log level is not defined
.PARAMETER DateTimeFormat
Format of the timestamp to be displayed in the log File or in optional console output
.PARAMETER NoLogInfo
Disable logging time and level in the log File or in optional console output
.PARAMETER Encoding
Text encoding to write to the log File with
.PARAMETER LogRoll
Enables automatic rolling of the log if set to True.
.PARAMETER LogRetry
Number of times to retry writing to the log File. Will wait half a second before trying again. Defaults to 2.
.PARAMETER WriteConsole
Switch to write the output to the console
.PARAMETER ConsoleOnly
Switch to write the output to the console only without logging to the log file
.PARAMETER ConsoleInfo
Switch to write the timestamp and log level during WriteConsole
.PARAMETER LogRotateOpt
Size of the log file with unit indicator letter or integer of the number of days to rotate the log file (e.g. 10M = 10 Megabytes or 7 = 7 days)
.PARAMETER LogZip
Keeping rotated logs inside of a compressed zip archive
.PARAMETER LogCountMax
Maximum number of rotated log files to keep
.OUTPUTS
Intialized log class that can be passed to the Write-Log function
.EXAMPLE
# Initialize a default log with default settings
Initialize-Log -Default
Write-Log "This message will go to the default log (Debug.log)"
.EXAMPLE
# Initialize a custom named log
$AppLog = Initialize-Log -LogName "Application"
Write-Log "This message goes to Application.log" -Logger $AppLog
.EXAMPLE
# Initialize a log with custom name and path
$CustomPathLog = Initialize-Log -LogName "Process" -LogPath "D:\Logs\System"
Write-Log "This message goes to D:\Logs\System\Process.log" -Logger $CustomPathLog
.EXAMPLE
# Initialize a log with a custom name and a different default log level
$ErrorLog = Initialize-Log -LogName "Errors" -LogLevel "ERROR"
Write-Log "This will be logged as an ERROR" -Logger $ErrorLog
.EXAMPLE
# Initialize a log with a custom name and a custom date/time format
$CustomTimeLog = Initialize-Log -LogName "TimeLog" -DateTimeFormat "MM/dd/yyyy HH:mm:ss"
Write-Log "This will have a custom timestamp format" -Logger $CustomTimeLog
.EXAMPLE
# Initialize a log a custom name and without timestamp and level in log entries
$CleanLog = Initialize-Log -LogName "Clean" -NoLogInfo
Write-Log "This message will appear without timestamp or level prefix" -Logger $CleanLog
.EXAMPLE
# Initialize a log with console output
$ConsoleLog = Initialize-Log -LogName "Console" -WriteConsole
Write-Log "This appears in both the log file and console" -Logger $ConsoleLog
.EXAMPLE
# Initialize a log with console-only output (no file writing)
$ConsoleOnlyLog = Initialize-Log -LogName "ConsoleOnly" -WriteConsole -ConsoleOnly
Write-Log "This only appears in the console, not in any log file" -Logger $ConsoleOnlyLog
.EXAMPLE
# Initialize a log with console output including timestamp and level
$VerboseConsoleLog = Initialize-Log -LogName "VerboseConsole" -WriteConsole -ConsoleInfo
Write-Log "This shows in console with timestamp and level" -Logger $VerboseConsoleLog
.EXAMPLE
# Initialize a log with log rotation by size
$RotatingLog = Initialize-Log -LogName "Rotating" -LogRoll $True -LogRotateOpt "10M"
Write-Log "This log will rotate when it reaches 10MB" -Logger $RotatingLog
.EXAMPLE
# Initialize a log with rotation by days
$DailyLog = Initialize-Log -LogName "Daily" -LogRoll $True -LogRotateOpt "1"
Write-Log "This log will rotate daily" -Logger $DailyLog
.EXAMPLE
# Initialize a log with rotation and zip archiving
$ZipLog = Initialize-Log -LogName "ZippedLogs" -LogRoll $True -LogRotateOpt "5M" -LogZip $True
Write-Log "Rotated logs will be stored in a zip archive" -Logger $ZipLog
.EXAMPLE
# Initialize a log with custom retry count
$RetryLog = Initialize-Log -LogName "Retry" -LogRetry 5
Write-Log "Will try 5 times if writing to log fails" -Logger $RetryLog
.EXAMPLE
# Initialize a log with custom encoding
$Utf8Log = Initialize-Log -LogName "UTF8Log" -Encoding "utf8"
Write-Log "This will be written with UTF-8 encoding" -Logger $Utf8Log
.EXAMPLE
# Initialize a log with a limit on the number of rotated files
$LimitedLog = Initialize-Log -LogName "Limited" -LogRoll $True -LogCountMax 3
Write-Log "Only 3 rotated log files will be kept" -Logger $LimitedLog
.EXAMPLE
# Initialize a default log and access it from anywhere in the script
Initialize-Log -Default -LogName "GlobalLog" -WriteConsole
# Later in the script, without passing a Logger object:
Write-Log "This uses the default log configuration"
#>
Param(
[alias ('D')][switch] $Default,
[alias ('LN')][string] $LogName = "Debug",
[alias ('LP')][string] $LogPath = "C:\Temp",
[alias ('LL', 'LogLvl')][string] $LogLevel = "INFO",
[Alias('TF', 'DF', 'DateFormat', 'TimeFormat')][string] $DateTimeFormat = 'yyyy-MM-dd HH:mm:ss',
[alias ('NLI')][switch] $NoLogInfo,
[ValidateSet('unknown', 'string', 'unicode', 'bigendianunicode', 'utf8', 'utf7', 'utf32', 'ascii', 'default', 'oem')][string]$Encoding = 'Unicode',
[alias ('Retry')][int] $LogRetry = 2,
[alias('WC', 'Console')][switch] $WriteConsole,
[alias('CO')][switch] $ConsoleOnly,
[alias('CI')][switch] $ConsoleInfo,
[alias ('LR', 'Roll')][switch] $LogRoll,
[alias ('RotateOpt')][string] $LogRotateOpt = "1M",
[alias('Zip')][switch] $LogZip,
[alias('LF', 'LogFiles')][int]$LogCountMax = 5
)
# Create a new logger instance
$Logger = [Logger]::new()
# Set all properties from parameters
$Logger.LogName = $LogName
$Logger.LogPath = $LogPath
$Logger.LogLevel = $LogLevel
$Logger.DateTimeFormat = $DateTimeFormat
$Logger.NoLogInfo = $NoLogInfo
$Logger.Encoding = $Encoding
$Logger.LogRoll = $LogRoll
$Logger.LogRetry = $LogRetry
$Logger.WriteConsole = $WriteConsole
$Logger.ConsoleOnly = $ConsoleOnly
$Logger.ConsoleInfo = $ConsoleInfo
$Logger.LogRotateOpt = $LogRotateOpt
$Logger.LogZip = $LogZip
$Logger.LogCountMax = $LogCountMax
If ($Default) {
$Script:DefaultLog = $Logger
Return
}
Return $Logger
}
Function Write-Log {
<#
.DESCRIPTION
Writes output to a log File provided by the logger class. The logger needs to be intialized with Intialize-Logger function first
and either be configured as the default log file or the logger class that is returned has to be passed to this function to specify
the log to write to.
.PARAMETER LogMsg
Message to be written to the log
.PARAMETER LogLevel
Name of a label to indicate the severity of the log
.PARAMETER Logger
Log class to be used to write to a log file. If a default log class was not initialized, this is a require parameter.
.EXAMPLE
# Writing to the default log class if one was initialized
Write-Log "This will write a INFO level message to the default log called debug.log"
Write-Log "This will write a WARNING level message to the default log called debug.log" -LogLevel "WARNING"
.EXAMPLE
# Writing to a non-default log class
$DebugLog = Initialize-Log -LogName "Debug"
Write-Log "This will write a WARNING level message to a log called Debug.log" -LogLevel "WARNING" -Logger $DebugLog
#>
Param(
[alias ('LM', 'Msg', 'Message')][Parameter(Mandatory=$True)][String] $LogMsg,
[alias ('LL', 'LogLvl', 'Level')][string] $LogLevel = "INFO",
[alias ('L', 'Log')] $Logger = $Script:DefaultLog
)
If (-not $Logger) {
Write-Error "No log class has been initialized. Initialize a default log class or provide an initialized log class."
} Else {
# Write the log entry
$Logger.Write($LogMsg, $LogLevel)
}
}
#endregion
# ================================
# === HELPER FUNCTIONS ===
# ================================
#region Helper Functions
Function Get-MsiExitCodeDescription {
<#
.SYNOPSIS
Returns a description for MSI installer exit codes
.DESCRIPTION
Provides human-readable descriptions for Windows Installer (msiexec) exit codes
based on Microsoft documentation
.PARAMETER ExitCode
The exit code returned by msiexec
.EXAMPLE
Get-MsiExitCodeDescription -ExitCode 1619
Returns: "This installation package could not be opened. Verify that the package exists and is accessible."
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[Int32]$ExitCode
)
$ExitCodes = @{
0 = 'Success. The action completed successfully.'
13 = 'The data is invalid.'
87 = 'One of the parameters was invalid.'
120 = 'This value is returned when a custom action attempts to call a function that cannot be called from custom actions. The function returns the value ERROR_CALL_NOT_IMPLEMENTED.'
1259 = 'If Windows Installer determines a product may be incompatible with the current operating system, it displays a dialog box informing the user and asking whether to try to install anyway. This error code is returned if the user chooses not to try the installation.'
1601 = 'The Windows Installer service could not be accessed. Contact your support personnel to verify that the Windows Installer service is properly registered.'
1602 = 'User cancelled installation.'
1603 = 'A fatal error occurred during installation.'
1604 = 'Installation suspended, incomplete.'
1605 = 'This action is only valid for products that are currently installed.'
1606 = 'Feature ID not registered.'
1607 = 'Component ID not registered.'
1608 = 'Unknown property.'
1609 = 'Handle is in an invalid state.'
1610 = 'The configuration data for this product is corrupt. Contact your support personnel.'
1611 = 'Component qualifier not present.'
1612 = 'The installation source for this product is not available. Verify that the source exists and that you can access it.'
1613 = 'This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.'
1614 = 'Product is uninstalled.'
1615 = 'SQL query syntax invalid or unsupported.'
1616 = 'Record field does not exist.'
1618 = 'Another installation is already in progress. Complete that installation before proceeding with this install.'
1619 = 'This installation package could not be opened. Verify that the package exists and is accessible, or contact the application vendor to verify that this is a valid Windows Installer package.'
1620 = 'This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.'
1621 = 'There was an error starting the Windows Installer service user interface. Contact your support personnel.'
1622 = 'There was an error opening installation log file. Verify that the specified log file location exists and is writable.'
1623 = 'This language of this installation package is not supported by your system.'
1624 = 'There was an error applying transforms. Verify that the specified transform paths are valid.'
1625 = 'This installation is forbidden by system policy. Contact your system administrator.'
1626 = 'Function could not be executed.'
1627 = 'Function failed during execution.'
1628 = 'Invalid or unknown table specified.'
1629 = 'Data supplied is of wrong type.'
1630 = 'Data of this type is not supported.'
1631 = 'The Windows Installer service failed to start. Contact your support personnel.'
1632 = 'The Temp folder is either full or inaccessible. Verify that the Temp folder exists and that you can write to it.'
1633 = 'This installation package is not supported on this platform. Contact your application vendor.'
1634 = 'Component is not used on this machine.'
1635 = 'This patch package could not be opened. Verify that the patch package exists and is accessible, or contact the application vendor to verify that this is a valid Windows Installer patch package.'
1636 = 'This patch package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer patch package.'
1637 = 'This patch package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.'
1638 = 'Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs in Control Panel.'
1639 = 'Invalid command line argument. Consult the Windows Installer SDK for detailed command-line help.'
1640 = 'The current user is not permitted to perform installations from a client session of a server running the Terminal Server role service.'
1641 = 'The installer has initiated a restart. This message is indicative of a success.'
1642 = 'The installer cannot install the upgrade patch because the program being upgraded may be missing or the upgrade patch updates a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade patch.'
1643 = 'The patch package is not permitted by system policy.'
1644 = 'One or more customizations are not permitted by system policy.'
1645 = 'Windows Installer does not permit installation from a Remote Desktop Connection.'
1646 = 'The patch package is not a removable patch package. Available beginning with Windows Installer version 3.0.'
1647 = 'The patch is not applied to this product. Available beginning with Windows Installer version 3.0.'
1648 = 'No valid sequence could be found for the set of patches. Available beginning with Windows Installer version 3.0.'
1649 = 'Patch removal was disallowed by policy. Available beginning with Windows Installer version 3.0.'
1650 = 'The XML patch data is invalid. Available beginning with Windows Installer version 3.0.'
1651 = 'Administrative user failed to apply patch for a per-user managed or a per-machine application that is in advertise state. Available beginning with Windows Installer version 3.0.'
1652 = 'Windows Installer is not accessible when the computer is in Safe Mode. Exit Safe Mode and try again or try using System Restore to return your computer to a previous state. Available beginning with Windows Installer version 4.0.'
1653 = 'Could not perform a multiple-package transaction because rollback has been disabled. Multiple-Package Installations cannot run if rollback is disabled. Available beginning with Windows Installer version 4.5.'
1654 = 'The app that you are trying to run is not supported on this version of Windows. A Windows Installer package, patch, or transform that has not been signed by Microsoft cannot be installed on an ARM computer.'
3010 = 'A restart is required to complete the install. This message is indicative of a success. This does not include installs where the ForceReboot action is run.'
3011 = 'The requested operation is successful. Changes will not be effective until the system is rebooted.'
}
If ($ExitCodes.ContainsKey($ExitCode)) {
Return $ExitCodes[$ExitCode]
} Else {
Return "Unknown exit code. Please refer to Windows Installer documentation for exit code: $ExitCode"
}
}
Function Get-MsiLogPath {
<#
.SYNOPSIS
Generates a unique MSI log file path for debugging installations
.DESCRIPTION
Creates a timestamped log file path for MSI installations to help with debugging
.PARAMETER MsiFileName
The name of the MSI file being installed
.PARAMETER Operation
The operation type (Install, Uninstall, Update)
.EXAMPLE
Get-MsiLogPath -MsiFileName "OpenJDK8U-jre_x64.msi" -Operation "Install"
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[String]$MsiFileName,
[Parameter(Mandatory = $true)]
[ValidateSet('Install', 'Uninstall', 'Update')]
[String]$Operation
)
# Ensure log directory exists
If (-not (Test-Path $Script:LogPath)) {
New-Item -Path $Script:LogPath -ItemType Directory -Force | Out-Null
}
# Create MSI logs subdirectory
$MsiLogDir = Join-Path $Script:LogPath 'MSI_Logs'
If (-not (Test-Path $MsiLogDir)) {
New-Item -Path $MsiLogDir -ItemType Directory -Force | Out-Null
}
# Generate unique log filename with timestamp
$Timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$SafeMsiName = [System.IO.Path]::GetFileNameWithoutExtension($MsiFileName)
$LogFileName = "${SafeMsiName}_${Operation}_${Timestamp}.log"
Return Join-Path $MsiLogDir $LogFileName
}
Function Get-HttpClientDownload {
<#
.SYNOPSIS
Downloads a file using System.Net.Http.HttpClient
.DESCRIPTION
A simple, efficient file download function using the modern System.Net.Http.HttpClient
class. Compatible with PowerShell 5.1+ and .NET Framework 4.5+. Provides better
performance and connection management compared to deprecated WebClient or Invoke-WebRequest.
.PARAMETER Url
The URL of the file to download
.PARAMETER OutputPath
The full path where the file will be saved
.PARAMETER TimeoutSeconds
Request timeout in seconds (default: 300)
.PARAMETER BufferSize
Buffer size for reading response stream in bytes (default: 65536)
.PARAMETER ProgressBar
Switch parameter to show download progress bar (default: false)
.PARAMETER UserAgent
Custom user agent string (default: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.3)
.PARAMETER Headers
Additional headers to include in the request as a hashtable
.PARAMETER OverwriteExisting
Overwrite existing file without prompting (default: false)
.EXAMPLE
Get-HttpClientDownload -Url 'https://example.com/file.zip' -OutputPath 'C:\Downloads\file.zip'