-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wutil.ps1
15066 lines (13977 loc) · 621 KB
/
Wutil.ps1
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
################################################################################################################
### ###
### WARNING: This file is automatically generated DO NOT modify this file directly as it will be overwritten ###
### ###
################################################################################################################
<#
.NOTES
Author : Chris Titus @christitustech
Runspace Author: @DeveloperDurp
GitHub : https://github.com/ChrisTitusTech
Version : 24.09.12
#>
param (
[switch]$Debug,
[string]$Config,
[switch]$Run
)
# Set DebugPreference based on the -Debug switch
if ($Debug) {
$DebugPreference = "Continue"
}
if ($Config) {
$PARAM_CONFIG = $Config
}
$PARAM_RUN = $false
# Handle the -Run switch
if ($Run) {
Write-Host "Running config file tasks..."
$PARAM_RUN = $true
}
# Load DLLs
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
# Variable to sync between runspaces
$sync = [Hashtable]::Synchronized(@{})
$sync.PSScriptRoot = $PSScriptRoot
$sync.version = "24.09.12"
$sync.configs = @{}
$sync.ProcessRunning = $false
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Output "Winutil needs to be run as Administrator. Attempting to relaunch."
$argList = @()
$PSBoundParameters.GetEnumerator() | ForEach-Object {
$argList += if ($_.Value -is [switch] -and $_.Value) {
"-$($_.Key)"
} elseif ($_.Value) {
"-$($_.Key) `"$($_.Value)`""
}
}
$script = if ($MyInvocation.MyCommand.Path) {
"& { & '$($MyInvocation.MyCommand.Path)' $argList }"
} else {
"iex '& { $(irm https://github.com/ChrisTitusTech/winutil/releases/latest/download/winutil.ps1) } $argList'"
}
$powershellcmd = if (Get-Command pwsh -ErrorAction SilentlyContinue) { "pwsh" } else { "powershell" }
$processCmd = if (Get-Command wt.exe -ErrorAction SilentlyContinue) { "wt.exe" } else { $powershellcmd }
Start-Process $processCmd -ArgumentList "$powershellcmd -ExecutionPolicy Bypass -NoProfile -Command $script" -Verb RunAs
break
}
$dateTime = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$logdir = "$env:localappdata\winutil\logs"
[System.IO.Directory]::CreateDirectory("$logdir") | Out-Null
Start-Transcript -Path "$logdir\winutil_$dateTime.log" -Append -NoClobber | Out-Null
# Set PowerShell window title
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Admin)"
clear-host
function Copy-Files {
<#
.DESCRIPTION
This function will make all modifications to the registry
.EXAMPLE
Set-WinUtilRegistry -Name "PublishUserActivities" -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Type "DWord" -Value "0"
#>
param (
[string]$Path,
[string]$Destination,
[switch]$Recurse = $false,
[switch]$Force = $false
)
try {
$files = Get-ChildItem -Path $path -Recurse:$recurse
Write-Host "Copy $($files.Count)(s) from $path to $destination"
foreach ($file in $files) {
$status = "Copy files {0} on {1}: {2}" -f $counter, $files.Count, $file.Name
Write-Progress -Activity "Copy Windows files" -Status $status -PercentComplete ($counter++/$files.count*100)
$restpath = $file.FullName -Replace $path, ''
if ($file.PSIsContainer -eq $true) {
Write-Debug "Creating $($destination + $restpath)"
New-Item ($destination+$restpath) -Force:$force -Type Directory -ErrorAction SilentlyContinue
} else {
Write-Debug "Copy from $($file.FullName) to $($destination+$restpath)"
Copy-Item $file.FullName ($destination+$restpath) -ErrorAction SilentlyContinue -Force:$force
Set-ItemProperty -Path ($destination+$restpath) -Name IsReadOnly -Value $false
}
}
Write-Progress -Activity "Copy Windows files" -Status "Ready" -Completed
} catch {
Write-Warning "Unable to Copy all the files due to unhandled exception"
Write-Warning $psitem.Exception.StackTrace
}
}
function Get-LocalizedYesNo {
<#
.SYNOPSIS
This function runs choice.exe and captures its output to extract yes no in a localized Windows
.DESCRIPTION
The function retrieves the output of the command 'cmd /c "choice <nul 2>nul"' and converts the default output for Yes and No
in the localized format, such as "Yes=<first character>, No=<second character>".
.EXAMPLE
$yesNoArray = Get-LocalizedYesNo
Write-Host "Yes=$($yesNoArray[0]), No=$($yesNoArray[1])"
#>
# Run choice and capture its options as output
# The output shows the options for Yes and No as "[Y,N]?" in the (partitially) localized format.
# eg. English: [Y,N]?
# Dutch: [Y,N]?
# German: [J,N]?
# French: [O,N]?
# Spanish: [S,N]?
# Italian: [S,N]?
# Russian: [Y,N]?
$line = cmd /c "choice <nul 2>nul"
$charactersArray = @()
$regexPattern = '([a-zA-Z])'
$charactersArray = [regex]::Matches($line, $regexPattern) | ForEach-Object { $_.Groups[1].Value }
Write-Debug "According to takeown.exe local Yes is $charactersArray[0]"
# Return the array of characters
return $charactersArray
}
function Get-Oscdimg {
<#
.DESCRIPTION
This function will download oscdimg file from github Release folders and put it into env:temp folder
.EXAMPLE
Get-Oscdimg
#>
param(
[Parameter(Mandatory, position=0)]
[string]$oscdimgPath
)
$oscdimgPath = "$env:TEMP\oscdimg.exe"
$downloadUrl = "https://github.com/ChrisTitusTech/winutil/raw/main/releases/oscdimg.exe"
Invoke-RestMethod -Uri $downloadUrl -OutFile $oscdimgPath
$hashResult = Get-FileHash -Path $oscdimgPath -Algorithm SHA256
$sha256Hash = $hashResult.Hash
Write-Host "[INFO] oscdimg.exe SHA-256 Hash: $sha256Hash"
$expectedHash = "AB9E161049D293B544961BFDF2D61244ADE79376D6423DF4F60BF9B147D3C78D" # Replace with the actual expected hash
if ($sha256Hash -eq $expectedHash) {
Write-Host "Hashes match. File is verified."
} else {
Write-Host "Hashes do not match. File may be corrupted or tampered with."
}
}
Function Get-WinUtilCheckBoxes {
<#
.SYNOPSIS
Finds all checkboxes that are checked on the specific tab and inputs them into a script.
.PARAMETER unCheck
Whether to uncheck the checkboxes that are checked. Defaults to true
.OUTPUTS
A List containing the name of each checked checkbox
.EXAMPLE
Get-WinUtilCheckBoxes "WPFInstall"
#>
Param(
[boolean]$unCheck = $false
)
$Output = @{
Install = @()
WPFTweaks = @()
WPFFeature = @()
WPFInstall = @()
}
$CheckBoxes = $sync.GetEnumerator() | Where-Object { $_.Value -is [System.Windows.Controls.CheckBox] }
# First check and add WPFTweaksRestorePoint if checked
$RestorePoint = $CheckBoxes | Where-Object { $_.Key -eq 'WPFTweaksRestorePoint' -and $_.Value.IsChecked -eq $true }
if ($RestorePoint) {
$Output["WPFTweaks"] = @('WPFTweaksRestorePoint')
Write-Debug "Adding WPFTweaksRestorePoint as first in WPFTweaks"
if ($unCheck) {
$RestorePoint.Value.IsChecked = $false
}
}
foreach ($CheckBox in $CheckBoxes) {
if ($CheckBox.Key -eq 'WPFTweaksRestorePoint') { continue } # Skip since it's already handled
$group = if ($CheckBox.Key.StartsWith("WPFInstall")) { "Install" }
elseif ($CheckBox.Key.StartsWith("WPFTweaks")) { "WPFTweaks" }
elseif ($CheckBox.Key.StartsWith("WPFFeature")) { "WPFFeature" }
if ($group) {
if ($CheckBox.Value.IsChecked -eq $true) {
$feature = switch ($group) {
"Install" {
# Get the winget value
[PsCustomObject]@{
winget="$($sync.configs.applications.$($CheckBox.Name).winget)";
choco="$($sync.configs.applications.$($CheckBox.Name).choco)";
}
}
default {
$CheckBox.Name
}
}
if (-not $Output.ContainsKey($group)) {
$Output[$group] = @()
}
if ($group -eq "Install") {
$Output["WPFInstall"] += $CheckBox.Name
Write-Debug "Adding: $($CheckBox.Name) under: WPFInstall"
}
Write-Debug "Adding: $($feature) under: $($group)"
$Output[$group] += $feature
if ($unCheck) {
$CheckBox.Value.IsChecked = $false
}
}
}
}
return $Output
}
function Get-WinUtilInstallerProcess {
<#
.SYNOPSIS
Checks if the given process is running
.PARAMETER Process
The process to check
.OUTPUTS
Boolean - True if the process is running
#>
param($Process)
if ($Null -eq $Process) {
return $false
}
if (Get-Process -Id $Process.Id -ErrorAction SilentlyContinue) {
return $true
}
return $false
}
Function Get-WinUtilToggleStatus {
<#
.SYNOPSIS
Pulls the registry keys for the given toggle switch and checks whether the toggle should be checked or unchecked
.PARAMETER ToggleSwitch
The name of the toggle to check
.OUTPUTS
Boolean to set the toggle's status to
#>
Param($ToggleSwitch)
if($ToggleSwitch -eq "WPFToggleDarkMode") {
$app = (Get-ItemProperty -path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize').AppsUseLightTheme
$system = (Get-ItemProperty -path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize').SystemUsesLightTheme
if($app -eq 0 -and $system -eq 0) {
return $true
} else {
return $false
}
}
if($ToggleSwitch -eq "WPFToggleBingSearch") {
$bingsearch = (Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Search').BingSearchEnabled
if($bingsearch -eq 0) {
return $false
} else {
return $true
}
}
if($ToggleSwitch -eq "WPFToggleNumLock") {
$numlockvalue = (Get-ItemProperty -path 'HKCU:\Control Panel\Keyboard').InitialKeyboardIndicators
if($numlockvalue -eq 2) {
return $true
} else {
return $false
}
}
if($ToggleSwitch -eq "WPFToggleVerboseLogon") {
$VerboseStatusvalue = (Get-ItemProperty -path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System').VerboseStatus
if($VerboseStatusvalue -eq 1) {
return $true
} else {
return $false
}
}
if($ToggleSwitch -eq "WPFToggleShowExt") {
$hideextvalue = (Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced').HideFileExt
if($hideextvalue -eq 0) {
return $true
} else {
return $false
}
}
if($ToggleSwitch -eq "WPFToggleSnapWindow") {
$hidesnap = (Get-ItemProperty -path 'HKCU:\Control Panel\Desktop').WindowArrangementActive
if($hidesnap -eq 0) {
return $false
} else {
return $true
}
}
if($ToggleSwitch -eq "WPFToggleSnapFlyout") {
$hidesnap = (Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced').EnableSnapAssistFlyout
if($hidesnap -eq 0) {
return $false
} else {
return $true
}
}
if($ToggleSwitch -eq "WPFToggleSnapSuggestion") {
$hidesnap = (Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced').SnapAssist
if($hidesnap -eq 0) {
return $false
} else {
return $true
}
}
if($ToggleSwitch -eq "WPFToggleMouseAcceleration") {
$MouseSpeed = (Get-ItemProperty -path 'HKCU:\Control Panel\Mouse').MouseSpeed
$MouseThreshold1 = (Get-ItemProperty -path 'HKCU:\Control Panel\Mouse').MouseThreshold1
$MouseThreshold2 = (Get-ItemProperty -path 'HKCU:\Control Panel\Mouse').MouseThreshold2
if($MouseSpeed -eq 1 -and $MouseThreshold1 -eq 6 -and $MouseThreshold2 -eq 10) {
return $true
} else {
return $false
}
}
if($ToggleSwitch -eq "WPFToggleTaskbarSearch") {
$SearchButton = (Get-ItemProperty -path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search").SearchboxTaskbarMode
if($SearchButton -eq 0) {
return $false
} else {
return $true
}
}
if ($ToggleSwitch -eq "WPFToggleStickyKeys") {
$StickyKeys = (Get-ItemProperty -path 'HKCU:\Control Panel\Accessibility\StickyKeys').Flags
if($StickyKeys -eq 58) {
return $false
} else {
return $true
}
}
if ($ToggleSwitch -eq "WPFToggleTaskView") {
$TaskView = (Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced').ShowTaskViewButton
if($TaskView -eq 0) {
return $false
} else {
return $true
}
}
if ($ToggleSwitch -eq "WPFToggleHiddenFiles") {
$HiddenFiles = (Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced').Hidden
if($HiddenFiles -eq 0) {
return $false
} else {
return $true
}
}
if ($ToggleSwitch -eq "WPFToggleTaskbarWidgets") {
$TaskbarWidgets = (Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced").TaskBarDa
if($TaskbarWidgets -eq 0) {
return $false
} else {
return $true
}
}
if ($ToggleSwitch -eq "WPFToggleTaskbarAlignment") {
$TaskbarAlignment = (Get-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced").TaskbarAl
if($TaskbarAlignment -eq 0) {
return $false
} else {
return $true
}
}
if ($ToggleSwitch -eq "WPFToggleDetailedBSoD") {
$DetailedBSoD1 = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl').DisplayParameters
$DetailedBSoD2 = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\CrashControl').DisableEmoticon
if (($DetailedBSoD1 -eq 0) -or ($DetailedBSoD2 -eq 0) -or !$DetailedBSoD1 -or !$DetailedBSoD2) {
return $false
} else {
return $true
}
}
}
function Get-WinUtilVariables {
<#
.SYNOPSIS
Gets every form object of the provided type
.OUTPUTS
List containing every object that matches the provided type
#>
param (
[Parameter()]
[string[]]$Type
)
$keys = ($sync.keys).where{ $_ -like "WPF*" }
if ($Type) {
$output = $keys | ForEach-Object {
try {
$objType = $sync["$psitem"].GetType().Name
if ($Type -contains $objType) {
Write-Output $psitem
}
} catch {
<#I am here so errors don't get outputted for a couple variables that don't have the .GetType() attribute#>
}
}
return $output
}
return $keys
}
function Get-WinUtilWingetLatest {
<#
.SYNOPSIS
Uses GitHub API to check for the latest release of Winget.
.DESCRIPTION
This function grabs the latest version of Winget and returns the download path to Install-WinUtilWinget for installation.
#>
# Invoke-WebRequest is notoriously slow when the byte progress is displayed. The following lines disable the progress bar and reset them at the end of the function
$PreviousProgressPreference = $ProgressPreference
$ProgressPreference = "silentlyContinue"
try {
# Grabs the latest release of Winget from the Github API for the install process.
$response = Invoke-RestMethod -Uri "https://api.github.com/repos/microsoft/Winget-cli/releases/latest" -Method Get -ErrorAction Stop
$latestVersion = $response.tag_name #Stores version number of latest release.
$licenseWingetUrl = $response.assets.browser_download_url | Where-Object {$_ -like "*License1.xml"} #Index value for License file.
Write-Host "Latest Version:`t$($latestVersion)`n"
Write-Host "Downloading..."
$assetUrl = $response.assets.browser_download_url | Where-Object {$_ -like "*Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle"}
Invoke-WebRequest -Uri $licenseWingetUrl -OutFile $ENV:TEMP\License1.xml
# The only pain is that the msixbundle for winget-cli is 246MB. In some situations this can take a bit, with slower connections.
Invoke-WebRequest -Uri $assetUrl -OutFile $ENV:TEMP\Microsoft.DesktopAppInstaller.msixbundle
} catch {
throw [WingetFailedInstall]::new('Failed to get latest Winget release and license')
}
$ProgressPreference = $PreviousProgressPreference
}
function Get-WinUtilWingetPrerequisites {
<#
.SYNOPSIS
Downloads the Winget Prereqs.
.DESCRIPTION
Downloads Prereqs for Winget. Version numbers are coded as variables and can be updated as uncommonly as Microsoft updates the prereqs.
#>
# I don't know of a way to detect the prereqs automatically, so if someone has a better way of defining these, that would be great.
# Microsoft.VCLibs version rarely changes, but for future compatibility I made it a variable.
$versionVCLibs = "14.00"
$fileVCLibs = "https://aka.ms/Microsoft.VCLibs.x64.${versionVCLibs}.Desktop.appx"
# Write-Host "$fileVCLibs"
# Microsoft.UI.Xaml version changed recently, so I made the version numbers variables.
$versionUIXamlMinor = "2.8"
$versionUIXamlPatch = "2.8.6"
$fileUIXaml = "https://github.com/microsoft/microsoft-ui-xaml/releases/download/v${versionUIXamlPatch}/Microsoft.UI.Xaml.${versionUIXamlMinor}.x64.appx"
# Write-Host "$fileUIXaml"
try {
Write-Host "Downloading Microsoft.VCLibs Dependency..."
Invoke-WebRequest -Uri $fileVCLibs -OutFile $ENV:TEMP\Microsoft.VCLibs.x64.Desktop.appx
Write-Host "Downloading Microsoft.UI.Xaml Dependency...`n"
Invoke-WebRequest -Uri $fileUIXaml -OutFile $ENV:TEMP\Microsoft.UI.Xaml.x64.appx
} catch {
throw [WingetFailedInstall]::new('Failed to install prerequsites')
}
}
function Get-WPFObjectName {
<#
.SYNOPSIS
This is a helper function that generates an objectname with the prefix WPF that can be used as a Powershell Variable after compilation.
To achieve this, all characters that are not a-z, A-Z or 0-9 are simply removed from the name.
.PARAMETER type
The type of object for which the name should be generated. (e.g. Label, Button, CheckBox...)
.PARAMETER name
The name or description to be used for the object. (invalid characters are removed)
.OUTPUTS
A string that can be used as a object/variable name in powershell.
For example: WPFLabelMicrosoftTools
.EXAMPLE
Get-WPFObjectName -type Label -name "Microsoft Tools"
#>
param(
[Parameter(Mandatory, position=0)]
[string]$type,
[Parameter(position=1)]
[string]$name
)
$Output = $("WPF"+$type+$name) -replace '[^a-zA-Z0-9]', ''
return $Output
}
function Install-WinUtilChoco {
<#
.SYNOPSIS
Installs Chocolatey if it is not already installed
#>
try {
Write-Host "Checking if Chocolatey is Installed..."
if((Test-WinUtilPackageManager -choco) -eq "installed") {
return
}
# Install logic taken from https://chocolatey.org/install#individual
Write-Host "Seems Chocolatey is not installed, installing now."
Set-ExecutionPolicy Bypass -Scope Process -Force;
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072;
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
} catch {
Write-Host "===========================================" -Foregroundcolor Red
Write-Host "-- Chocolatey failed to install ---" -Foregroundcolor Red
Write-Host "===========================================" -Foregroundcolor Red
}
}
function Install-WinUtilProgramChoco {
<#
.SYNOPSIS
Manages the installation or uninstallation of a list of Chocolatey packages.
.PARAMETER Programs
A string array containing the programs to be installed or uninstalled.
.PARAMETER Action
Specifies the action to perform: "Install" or "Uninstall". The default value is "Install".
.DESCRIPTION
This function processes a list of programs to be managed using Chocolatey. Depending on the specified action, it either installs or uninstalls each program in the list, updating the taskbar progress accordingly. After all operations are completed, temporary output files are cleaned up.
.EXAMPLE
Install-WinUtilProgramChoco -Programs @("7zip","chrome") -Action "Uninstall"
#>
param(
[Parameter(Mandatory, Position = 0)]
[string[]]$Programs,
[Parameter(Position = 1)]
[String]$Action = "Install"
)
function Initialize-OutputFile {
<#
.SYNOPSIS
Initializes an output file by removing any existing file and creating a new, empty file at the specified path.
.PARAMETER filePath
The full path to the file to be initialized.
.DESCRIPTION
This function ensures that the specified file is reset by removing any existing file at the provided path and then creating a new, empty file. It is useful when preparing a log or output file for subsequent operations.
.EXAMPLE
Initialize-OutputFile -filePath "C:\temp\output.txt"
#>
param ($filePath)
Remove-Item -Path $filePath -Force -ErrorAction SilentlyContinue
New-Item -ItemType File -Path $filePath | Out-Null
}
function Run-ChocoCommand {
<#
.SYNOPSIS
Executes a Chocolatey command with the specified arguments and returns the exit code.
.PARAMETER arguments
The arguments to be passed to the Chocolatey command.
.DESCRIPTION
This function runs a specified Chocolatey command by passing the provided arguments to the `choco` executable. It waits for the process to complete and then returns the exit code, allowing the caller to determine success or failure based on the exit code.
.RETURNS
[int]
The exit code of the Chocolatey command.
.EXAMPLE
$exitCode = Run-ChocoCommand -arguments "install 7zip -y"
#>
param ($arguments)
return (Start-Process -FilePath "choco" -ArgumentList $arguments -Wait -PassThru).ExitCode
}
function Check-UpgradeNeeded {
<#
.SYNOPSIS
Checks if an upgrade is needed for a Chocolatey package based on the content of a log file.
.PARAMETER filePath
The path to the log file that contains the output of a Chocolatey install command.
.DESCRIPTION
This function reads the specified log file and checks for keywords that indicate whether an upgrade is needed. It returns a boolean value indicating whether the terms "reinstall" or "already installed" are present, which suggests that the package might need an upgrade.
.RETURNS
[bool]
True if the log file indicates that an upgrade is needed; otherwise, false.
.EXAMPLE
$isUpgradeNeeded = Check-UpgradeNeeded -filePath "C:\temp\install-output.txt"
#>
param ($filePath)
return Get-Content -Path $filePath | Select-String -Pattern "reinstall|already installed" -Quiet
}
function Update-TaskbarProgress {
<#
.SYNOPSIS
Updates the taskbar progress based on the current installation progress.
.PARAMETER currentIndex
The current index of the program being installed or uninstalled.
.PARAMETER totalPrograms
The total number of programs to be installed or uninstalled.
.DESCRIPTION
This function calculates the progress of the installation or uninstallation process and updates the taskbar accordingly. The taskbar is set to "Normal" if all programs have been processed, otherwise, it is set to "Error" as a placeholder.
.EXAMPLE
Update-TaskbarProgress -currentIndex 3 -totalPrograms 10
#>
param (
[int]$currentIndex,
[int]$totalPrograms
)
$progressState = if ($currentIndex -eq $totalPrograms) { "Normal" } else { "Error" }
$sync.form.Dispatcher.Invoke([action] { Set-WinUtilTaskbaritem -state $progressState -value ($currentIndex / $totalPrograms) })
}
function Install-ChocoPackage {
<#
.SYNOPSIS
Installs a Chocolatey package and optionally upgrades it if needed.
.PARAMETER Program
A string containing the name of the Chocolatey package to be installed.
.PARAMETER currentIndex
The current index of the program in the list of programs to be managed.
.PARAMETER totalPrograms
The total number of programs to be installed.
.DESCRIPTION
This function installs a Chocolatey package by running the `choco install` command. If the installation output indicates that an upgrade might be needed, the function will attempt to upgrade the package. The taskbar progress is updated after each package is processed.
.EXAMPLE
Install-ChocoPackage -Program $Program -currentIndex 0 -totalPrograms 5
#>
param (
[string]$Program,
[int]$currentIndex,
[int]$totalPrograms
)
$installOutputFile = "$env:TEMP\Install-WinUtilProgramChoco.install-command.output.txt"
Initialize-OutputFile $installOutputFile
Write-Host "Starting installation of $Program with Chocolatey."
try {
$installStatusCode = Run-ChocoCommand "install $Program -y --log-file $installOutputFile"
if ($installStatusCode -eq 0) {
if (Check-UpgradeNeeded $installOutputFile) {
$upgradeStatusCode = Run-ChocoCommand "upgrade $Program -y"
Write-Host "$Program was" $(if ($upgradeStatusCode -eq 0) { "upgraded successfully." } else { "not upgraded." })
}
else {
Write-Host "$Program installed successfully."
}
}
else {
Write-Host "Failed to install $Program."
}
}
catch {
Write-Host "Failed to install $Program due to an error: $_"
}
finally {
Update-TaskbarProgress $currentIndex $totalPrograms
}
}
function Uninstall-ChocoPackage {
<#
.SYNOPSIS
Uninstalls a Chocolatey package and any related metapackages.
.PARAMETER Program
A string containing the name of the Chocolatey package to be uninstalled.
.PARAMETER currentIndex
The current index of the program in the list of programs to be managed.
.PARAMETER totalPrograms
The total number of programs to be uninstalled.
.DESCRIPTION
This function uninstalls a Chocolatey package and any related metapackages (e.g., .install or .portable variants). It updates the taskbar progress after processing each package.
.EXAMPLE
Uninstall-ChocoPackage -Program $Program -currentIndex 0 -totalPrograms 5
#>
param (
[string]$Program,
[int]$currentIndex,
[int]$totalPrograms
)
$uninstallOutputFile = "$env:TEMP\Install-WinUtilProgramChoco.uninstall-command.output.txt"
Initialize-OutputFile $uninstallOutputFile
Write-Host "Searching for metapackages of $Program (.install or .portable)"
$chocoPackages = ((choco list | Select-String -Pattern "$Program(\.install|\.portable)?").Matches.Value) -join " "
if ($chocoPackages) {
Write-Host "Starting uninstallation of $chocoPackages with Chocolatey."
try {
$uninstallStatusCode = Run-ChocoCommand "uninstall $chocoPackages -y"
Write-Host "$Program" $(if ($uninstallStatusCode -eq 0) { "uninstalled successfully." } else { "failed to uninstall." })
}
catch {
Write-Host "Failed to uninstall $Program due to an error: $_"
}
finally {
Update-TaskbarProgress $currentIndex $totalPrograms
}
}
else {
Write-Host "$Program is not installed."
}
}
$totalPrograms = $Programs.Count
if ($totalPrograms -le 0) {
throw "Parameter 'Programs' must have at least one item."
}
Write-Host "==========================================="
Write-Host "-- Configuring Chocolatey packages ---"
Write-Host "==========================================="
for ($currentIndex = 0; $currentIndex -lt $totalPrograms; $currentIndex++) {
$Program = $Programs[$currentIndex]
Set-WinUtilProgressBar -label "$Action $($Program)" -percent ($currentIndex / $totalPrograms * 100)
$sync.form.Dispatcher.Invoke([action]{ Set-WinUtilTaskbaritem -value ($currentIndex / $totalPrograms)})
switch ($Action) {
"Install" {
Install-ChocoPackage -Program $Program -currentIndex $currentIndex -totalPrograms $totalPrograms
}
"Uninstall" {
Uninstall-ChocoPackage -Program $Program -currentIndex $currentIndex -totalPrograms $totalPrograms
}
default {
throw "Invalid action parameter value: '$Action'."
}
}
}
Set-WinUtilProgressBar -label "$($Action)ation done" -percent 100
# Cleanup Output Files
$outputFiles = @("$env:TEMP\Install-WinUtilProgramChoco.install-command.output.txt", "$env:TEMP\Install-WinUtilProgramChoco.uninstall-command.output.txt")
foreach ($filePath in $outputFiles) {
Remove-Item -Path $filePath -Force -ErrorAction SilentlyContinue
}
}
Function Install-WinUtilProgramWinget {
<#
.SYNOPSIS
Runs the designated action on the provided programs using Winget
.PARAMETER Programs
A list of programs to process
.PARAMETER action
The action to perform on the programs, can be either 'Install' or 'Uninstall'
.NOTES
The triple quotes are required any time you need a " in a normal script block.
The winget Return codes are documented here: https://github.com/microsoft/winget-cli/blob/master/doc/windows/package-actionr/winget/returnCodes.md
#>
param(
[Parameter(Mandatory, Position=0)]$Programs,
[Parameter(Mandatory, Position=1)]
[ValidateSet("Install", "Uninstall")]
[String]$Action
)
Function Invoke-Winget {
<#
.SYNOPSIS
Invokes the winget.exe with the provided arguments and return the exit code
.PARAMETER wingetId
The Id of the Program that Winget should Install/Uninstall
.PARAMETER scope
Determines the installation mode. Can be "user" or "machine" (For more info look at the winget documentation)
.PARAMETER credential
The PSCredential Object of the user that should be used to run winget
.NOTES
Invoke Winget uses the public variable $Action defined outside the function to determine if a Program should be installed or removed
#>
param (
[string]$wingetId,
[string]$scope = "",
[PScredential]$credential = $null
)
$commonArguments = "--id $wingetId --silent"
$arguments = if ($Action -eq "Install") {
"install $commonArguments --accept-source-agreements --accept-package-agreements $(if ($scope) {" --scope $scope"})"
} else {
"uninstall $commonArguments"
}
$processParams = @{
FilePath = "winget"
ArgumentList = $arguments
Wait = $true
PassThru = $true
NoNewWindow = $true
}
if ($credential) {
$processParams.credential = $credential
}
return (Start-Process @processParams).ExitCode
}
Function Invoke-Install {
<#
.SYNOPSIS
Contains the Install Logic and return code handling from winget
.PARAMETER Program
The Winget ID of the Program that should be installed
#>
param (
[string]$Program
)
$status = Invoke-Winget -wingetId $Program
if ($status -eq 0) {
Write-Host "$($Program) installed successfully."
return $true
} elseif ($status -eq -1978335189) {
Write-Host "$($Program) No applicable update found"
return $true
}
Write-Host "Attempt installation of $($Program) with User scope"
$status = Invoke-Winget -wingetId $Program -scope "user"
if ($status -eq 0) {
Write-Host "$($Program) installed successfully with User scope."
return $true
} elseif ($status -eq -1978335189) {
Write-Host "$($Program) No applicable update found"
return $true
}
$userChoice = [System.Windows.MessageBox]::Show("Do you want to attempt $($Program) installation with specific user credentials? Select 'Yes' to proceed or 'No' to skip.", "User credential Prompt", [System.Windows.MessageBoxButton]::YesNo)
if ($userChoice -eq 'Yes') {
$getcreds = Get-Credential
$status = Invoke-Winget -wingetId $Program -credential $getcreds
if ($status -eq 0) {
Write-Host "$($Program) installed successfully with User prompt."
return $true
}
} else {
Write-Host "Skipping installation with specific user credentials."
}
Write-Host "Failed to install $($Program)."
return $false
}
Function Invoke-Uninstall {
<#
.SYNOPSIS
Contains the Uninstall Logic and return code handling from winget
.PARAMETER Program
The Winget ID of the Program that should be uninstalled
#>
param (
[psobject]$Program
)
try {
$status = Invoke-Winget -wingetId $Program
if ($status -eq 0) {
Write-Host "$($Program) uninstalled successfully."
return $true
} else {
Write-Host "Failed to uninstall $($Program)."
return $false
}
} catch {
Write-Host "Failed to uninstall $($Program) due to an error: $_"
return $false
}
}
$count = $Programs.Count
$failedPackages = @()
Write-Host "==========================================="
Write-Host "-- Configuring winget packages ---"
Write-Host "==========================================="
for ($i = 0; $i -lt $count; $i++) {
$Program = $Programs[$i]
$result = $false
Set-WinUtilProgressBar -label "$Action $($Program)" -percent ($i / $count * 100)
$sync.form.Dispatcher.Invoke([action]{ Set-WinUtilTaskbaritem -value ($i / $count)})