forked from ChrisTitusTech/winutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winutil.ps1
13253 lines (12390 loc) · 623 KB
/
winutil.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.04.21
#>
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
}
if (!(Test-Path -Path $ENV:TEMP)) {
New-Item -ItemType Directory -Force -Path $ENV:TEMP
}
Start-Transcript $ENV:TEMP\Winutil.log -Append
# 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.04.21"
$sync.configs = @{}
$sync.ProcessRunning = $false
$currentPid = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object System.Security.Principal.WindowsPrincipal($currentPid)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($principal.IsInRole($adminRole))
{
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Admin)"
clear-host
}
else
{
Write-Host "===========================================" -Foregroundcolor Red
Write-Host "-- Scripts must be run as Administrator ---" -Foregroundcolor Red
Write-Host "-- Right-Click Start -> Terminal(Admin) ---" -Foregroundcolor Red
Write-Host "===========================================" -Foregroundcolor Red
break
}
function ConvertTo-Icon {
<#
.DESCRIPTION
This function will convert PNG to ICO file
.EXAMPLE
ConvertTo-Icon -bitmapPath "$env:TEMP\cttlogo.png" -iconPath $iconPath
#>
param( [Parameter(Mandatory=$true)]
$bitmapPath,
$iconPath = "$env:temp\newicon.ico"
)
Add-Type -AssemblyName System.Drawing
if (Test-Path $bitmapPath) {
$b = [System.Drawing.Bitmap]::FromFile($bitmapPath)
$icon = [System.Drawing.Icon]::FromHandle($b.GetHicon())
$file = New-Object System.IO.FileStream($iconPath, 'OpenOrCreate')
$icon.Save($file)
$file.Close()
$icon.Dispose()
#explorer "/SELECT,$iconpath"
}
else { Write-Warning "$BitmapPath does not exist" }
}
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-LocalizedYesNoTakeown {
<#
.SYNOPSIS
This function runs takeown.exe and captures its output to extract yes no in a localized Windows
.DESCRIPTION
The function retrieves lines from the output of takeown.exe until there are at least 2 characters
captured in a specific format, such as "Yes=<first character>, No=<second character>".
.EXAMPLE
$yesNoArray = Get-LocalizedYesNo
Write-Host "Yes=$($yesNoArray[0]), No=$($yesNoArray[1])"
#>
# Run takeown.exe and capture its output
$takeownOutput = & takeown.exe /? | Out-String
# Parse the output and retrieve lines until there are at least 2 characters in the array
$found = $false
$charactersArray = @()
foreach ($line in $takeownOutput -split "`r`n")
{
# skip everything before /D flag help
if ($found)
{
# now that /D is found start looking for a single character in double quotes
# in help text there is another string in double quotes but it is not a single character
$regexPattern = '"([a-zA-Z])"'
$charactersArray = [regex]::Matches($line, $regexPattern) | ForEach-Object { $_.Groups[1].Value }
# if ($charactersArray.Count -gt 0) {
# Write-Output "Extracted symbols: $($matches -join ', ')"
# } else {
# Write-Output "No matches found."
# }
if ($charactersArray.Count -ge 2)
{
break
}
}
elseif ($line -match "/D ")
{
$found = $true
}
}
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=$true)]
[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-TabXaml {
<#
.SYNOPSIS
Generates XAML for a tab in the WinUtil GUI
This function is used to generate the XAML for the applications tab in the WinUtil GUI
It takes the tabname and the number of columns to display the applications in as input and returns the XAML for the tab as output
.PARAMETER tabname
The name of the tab to generate XAML for
.PARAMETER columncount
The number of columns to display the applications in
.OUTPUTS
The XAML for the tab
.EXAMPLE
Get-TabXaml "applications" 3
#>
param( [Parameter(Mandatory=$true)]
$tabname,
$columncount = 0
)
$organizedData = @{}
# Iterate through JSON data and organize by panel and category
foreach ($appName in $sync.configs.$tabname.PSObject.Properties.Name) {
$appInfo = $sync.configs.$tabname.$appName
# Create an object for the application
$appObject = [PSCustomObject]@{
Name = $appName
Category = $appInfo.Category
Content = $appInfo.Content
Choco = $appInfo.choco
Winget = $appInfo.winget
Panel = if ($columncount -gt 0 ) { "0" } else {$appInfo.panel}
Link = $appInfo.link
Description = $appInfo.description
# Type is (Checkbox,Toggle,Button,Combobox ) (Default is Checkbox)
Type = $appInfo.type
ComboItems = $appInfo.ComboItems
# Checked is the property to set startup checked status of checkbox (Default is false)
Checked = $appInfo.Checked
}
if (-not $organizedData.ContainsKey($appObject.panel)) {
$organizedData[$appObject.panel] = @{}
}
if (-not $organizedData[$appObject.panel].ContainsKey($appObject.Category)) {
$organizedData[$appObject.panel][$appObject.Category] = @{}
}
# Store application data in a sub-array under the category
# Add Order property to keep the original order of tweaks and features
$organizedData[$appObject.panel][$appInfo.Category]["$($appInfo.order)$appName"] = $appObject
}
$panelcount=0
$paneltotal = $organizedData.Keys.Count
if ($columncount -gt 0) {
$appcount = $sync.configs.$tabname.PSObject.Properties.Name.count + $organizedData["0"].Keys.count
$maxcount = [Math]::Round( $appcount / $columncount + 0.5)
$paneltotal = $columncount
}
# add ColumnDefinitions to evenly draw colums
$blockXml="<Grid.ColumnDefinitions>`n"+("<ColumnDefinition Width=""*""/>`n"*($paneltotal))+"</Grid.ColumnDefinitions>`n"
# Iterate through organizedData by panel, category, and application
$count = 0
foreach ($panel in ($organizedData.Keys | Sort-Object)) {
$blockXml += "<Border Grid.Row=""1"" Grid.Column=""$panelcount"">`n<StackPanel Background=""{MainBackgroundColor}"" SnapsToDevicePixels=""True"">`n"
$panelcount++
foreach ($category in ($organizedData[$panel].Keys | Sort-Object)) {
$count++
if ($columncount -gt 0) {
$panelcount2 = [Int](($count)/$maxcount-0.5)
if ($panelcount -eq $panelcount2 ) {
$blockXml +="`n</StackPanel>`n</Border>`n"
$blockXml += "<Border Grid.Row=""1"" Grid.Column=""$panelcount"">`n<StackPanel Background=""{MainBackgroundColor}"" SnapsToDevicePixels=""True"">`n"
$panelcount++
}
}
$blockXml += "<Label Content=""$($category -replace '^.__', '')"" FontSize=""16""/>`n"
$sortedApps = $organizedData[$panel][$category].Keys | Sort-Object
foreach ($appName in $sortedApps) {
$count++
if ($columncount -gt 0) {
$panelcount2 = [Int](($count)/$maxcount-0.5)
if ($panelcount -eq $panelcount2 ) {
$blockXml +="`n</StackPanel>`n</Border>`n"
$blockXml += "<Border Grid.Row=""1"" Grid.Column=""$panelcount"">`n<StackPanel Background=""{MainBackgroundColor}"" SnapsToDevicePixels=""True"">`n"
$panelcount++
}
}
$appInfo = $organizedData[$panel][$category][$appName]
if ("Toggle" -eq $appInfo.Type) {
$blockXml += "<StackPanel Orientation=`"Horizontal`" Margin=`"0,10,0,0`">`n<Label Content=`"$($appInfo.Content)`" Style=`"{StaticResource labelfortweaks}`" ToolTip=`"$($appInfo.Description)`" />`n"
$blockXml += "<CheckBox Name=`"$($appInfo.Name)`" Style=`"{StaticResource ColorfulToggleSwitchStyle}`" Margin=`"2.5,0`"/>`n</StackPanel>`n"
} elseif ("Combobox" -eq $appInfo.Type) {
$blockXml += "<StackPanel Orientation=`"Horizontal`" Margin=`"0,5,0,0`">`n<Label Content=`"$($appInfo.Content)`" HorizontalAlignment=`"Left`" VerticalAlignment=`"Center`"/>`n"
$blockXml += "<ComboBox Name=`"$($appInfo.Name)`" Height=`"32`" Width=`"186`" HorizontalAlignment=`"Left`" VerticalAlignment=`"Center`" Margin=`"5,5`">`n"
$addfirst="IsSelected=`"True`""
foreach ($comboitem in ($appInfo.ComboItems -split " ")) {
$blockXml += "<ComboBoxItem $addfirst Content=`"$comboitem`"/>`n"
$addfirst=""
}
$blockXml += "</ComboBox>`n</StackPanel>"
# If it is a digit, type is button and button length is digits
} elseif ($appInfo.Type -match "^[\d\.]+$") {
$blockXml += "<Button Name=`"$($appInfo.Name)`" Content=`"$($appInfo.Content)`" HorizontalAlignment = `"Left`" Width=`"$($appInfo.Type)`" Margin=`"5`" Padding=`"20,5`" />`n"
# else it is a checkbox
} else {
$checkedStatus = If ($null -eq $appInfo.Checked) {""} Else {"IsChecked=`"$($appInfo.Checked)`" "}
if ($null -eq $appInfo.Link)
{
$blockXml += "<CheckBox Name=`"$($appInfo.Name)`" Content=`"$($appInfo.Content)`" $($checkedStatus)Margin=`"5,0`" ToolTip=`"$($appInfo.Description)`"/>`n"
}
else
{
$blockXml += "<StackPanel Orientation=""Horizontal"">`n<CheckBox Name=""$($appInfo.Name)"" Content=""$($appInfo.Content)"" $($checkedStatus)ToolTip=""$($appInfo.Description)"" Margin=""0,0,2,0""/><TextBlock Name=""$($appInfo.Name)Link"" Style=""{StaticResource HoverTextBlockStyle}"" Text=""(?)"" ToolTip=""$($appInfo.Link)"" />`n</StackPanel>`n"
}
}
}
}
$blockXml +="`n</StackPanel>`n</Border>`n"
}
return ($blockXml)
}
Function Get-WinUtilCheckBoxes {
<#
.SYNOPSIS
Finds all checkboxes that are checked on the specific tab and inputs them into a script.
.PARAMETER Group
The group of checkboxes to check
.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] }
foreach ($CheckBox in $CheckBoxes) {
$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
$wingetValue = $sync.configs.applications.$($CheckBox.Name).winget
if (-not [string]::IsNullOrWhiteSpace($wingetValue) -and $wingetValue -ne "na") {
$wingetValue -split ";"
} else {
$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 -eq $true) {
$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 "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 "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 "WPFToggleStickyKeys") {
$StickyKeys = (Get-ItemProperty -path 'HKCU:\Control Panel\Accessibility\StickyKeys').Flags
if($StickyKeys -eq 58){
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
}
}
}
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-Object { $_ -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.
#>
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[0] #Index value for License file.
Write-Host "Latest Version:`t$($latestVersion)`n"
$assetUrl = $response.assets.browser_download_url[2] #Index value for download URL.
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')
}
}
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 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
}
Write-Host "Seems Chocolatey is not installed, installing now."
Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) -ErrorAction Stop
powershell choco feature enable -n allowGlobalConfirmation
}
Catch {
Write-Host "===========================================" -Foregroundcolor Red
Write-Host "-- Chocolatey failed to install ---" -Foregroundcolor Red
Write-Host "===========================================" -Foregroundcolor Red
}
}
Function Install-WinUtilProgramWinget {
<#
.SYNOPSIS
Manages the provided programs using Winget
.PARAMETER ProgramsToInstall
A list of programs to manage
.PARAMETER manage
The action to perform on the programs, can be either 'Installing' or 'Uninstalling'
.NOTES
The triple quotes are required any time you need a " in a normal script block.
#>
param(
$ProgramsToInstall,
$manage = "Installing"
)
$x = 0
$count = $($ProgramsToInstall -split ",").Count
Write-Progress -Activity "$manage Applications" -Status "Starting" -PercentComplete 0
Foreach ($Program in $($ProgramsToInstall -split ",")){
Write-Progress -Activity "$manage Applications" -Status "$manage $Program $($x + 1) of $count" -PercentComplete $($x/$count*100)
if($manage -eq "Installing"){
# Install package via ID, if it fails try again with different scope and then with an unelevated prompt.
# Since Install-WinGetPackage might not be directly available, we use winget install command as a workaround.
# Winget, not all installers honor any of the following: System-wide, User Installs, or Unelevated Prompt OR Silent Install Mode.
# This is up to the individual package maintainers to enable these options. Aka. not as clean as Linux Package Managers.
try {
$status = $(Start-Process -FilePath "winget" -ArgumentList "install --id $Program --silent --accept-source-agreements --accept-package-agreements" -Wait -PassThru).ExitCode
if($status -ne 0){
Write-Host "Attempt with User scope"
$status = $(Start-Process -FilePath "winget" -ArgumentList "install --id $Program --scope user --silent --accept-source-agreements --accept-package-agreements" -Wait -PassThru).ExitCode
if($status -ne 0){
Write-Host "Attempt with Unelevated prompt"
$status = $(Start-Process -FilePath "powershell" -ArgumentList "-Command Start-Process winget -ArgumentList 'install --id $Program --silent --accept-source-agreements --accept-package-agreements' -Verb runAsUser" -Wait -PassThru).ExitCode
if($status -ne 0){
Write-Host "Failed to install $Program."
} else {
Write-Host "$Program installed successfully with Unelevated prompt."
}
} else {
Write-Host "$Program installed successfully with User scope."
}
} else {
Write-Host "$Program installed successfully."
}
} catch {
Write-Host "Failed to install $Program due to an error: $_"
}
}
if($manage -eq "Uninstalling"){
# Uninstall package via ID using winget directly.
try {
$status = $(Start-Process -FilePath "winget" -ArgumentList "uninstall --id $Program --silent" -Wait -PassThru).ExitCode
if($status -ne 0){
Write-Host "Failed to uninstall $Program."
} else {
Write-Host "$Program uninstalled successfully."
}
} catch {
Write-Host "Failed to uninstall $Program due to an error: $_"
}
}
$X++
}
Write-Progress -Activity "$manage Applications" -Status "Finished" -Completed
}
function Install-WinUtilWinget {
<#
.SYNOPSIS
Installs Winget if it is not already installed.
.DESCRIPTION
This function will download the latest version of Winget and install it. If Winget is already installed, it will do nothing.
#>
$isWingetInstalled = Test-WinUtilPackageManager -winget
Try {
if ($isWingetInstalled -eq "installed") {
Write-Host "`nWinget is already installed.`r" -ForegroundColor Green
return
} elseif ($isWingetInstalled -eq "outdated") {
Write-Host "`nWinget is Outdated. Continuing with install.`r" -ForegroundColor Yellow
} else {
Write-Host "`nWinget is not Installed. Continuing with install.`r" -ForegroundColor Red
}
# Gets the computer's information
if ($null -eq $sync.ComputerInfo){
$ComputerInfo = Get-ComputerInfo -ErrorAction Stop
} else {
$ComputerInfo = $sync.ComputerInfo
}
if (($ComputerInfo.WindowsVersion) -lt "1809") {
# Checks if Windows Version is too old for Winget
Write-Host "Winget is not supported on this version of Windows (Pre-1809)" -ForegroundColor Red
return
}
# Install Winget via GitHub method.
# Used part of my own script with some modification: ruxunderscore/windows-initialization
Write-Host "Downloading Winget Prerequsites`n"
Get-WinUtilWingetPrerequisites
Write-Host "Downloading Winget and License File`r"
Get-WinUtilWingetLatest
Write-Host "Installing Winget w/ Prerequsites`r"
Add-AppxProvisionedPackage -Online -PackagePath $ENV:TEMP\Microsoft.DesktopAppInstaller.msixbundle -DependencyPackagePath $ENV:TEMP\Microsoft.VCLibs.x64.Desktop.appx, $ENV:TEMP\Microsoft.UI.Xaml.x64.appx -LicensePath $ENV:TEMP\License1.xml
Write-Host "Manually adding Winget Sources, from Winget CDN."
Add-AppxPackage -Path https://cdn.winget.microsoft.com/cache/source.msix #Seems some installs of Winget don't add the repo source, this should makes sure that it's installed every time.
Write-Host "Winget Installed" -ForegroundColor Green
Write-Host "Enabling NuGet and Module..."
Install-PackageProvider -Name NuGet -Force
Install-Module -Name Microsoft.WinGet.Client -Force
# Winget only needs a refresh of the environment variables to be used.
Write-Output "Refreshing Environment Variables...`n"
$ENV:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
} Catch {
Write-Host "Failure detected while installing via GitHub method. Continuing with Chocolatey method as fallback." -ForegroundColor Red
# In case install fails via GitHub method.
Try {
Start-Process -Verb runas -FilePath powershell.exe -ArgumentList "choco install winget-cli"
Write-Host "Winget Installed" -ForegroundColor Green
Write-Output "Refreshing Environment Variables...`n"
$ENV:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
} Catch {
throw [WingetFailedInstall]::new('Failed to install!')
}
}
}
function Invoke-MicroWin-Helper {
<#
.SYNOPSIS
checking unit tests
.PARAMETER Name
no parameters
.EXAMPLE
placeholder
#>
}
function Test-CompatibleImage() {
<#
.SYNOPSIS
Checks the version of a Windows image and determines whether or not it is compatible with a specific feature depending on a desired version
.PARAMETER Name
imgVersion - The version of the Windows image
desiredVersion - The version to compare the image version with
#>
param
(
[Parameter(Mandatory = $true, Position=0)] [string] $imgVersion,
[Parameter(Mandatory = $true, Position=1)] [Version] $desiredVersion
)
try {
$version = [Version]$imgVersion
return $version -ge $desiredVersion
} catch {
return $False
}
}
function Remove-Features([switch] $dumpFeatures = $false, [switch] $keepDefender = $false) {
<#
.SYNOPSIS
Removes certain features from ISO image
.PARAMETER Name
dumpFeatures - Dumps all features found in the ISO into a file called allfeaturesdump.txt. This file can be examined and used to decide what to remove.
keepDefender - Should Defender be removed from the ISO?
.EXAMPLE
Remove-Features -keepDefender:$false
#>
$featlist = (Get-WindowsOptionalFeature -Path $scratchDir).FeatureName
if ($dumpFeatures)
{
$featlist > allfeaturesdump.txt
}
$featlist = $featlist | Where-Object {
$_ -NotLike "*Printing*" -AND
$_ -NotLike "*TelnetClient*" -AND
$_ -NotLike "*PowerShell*" -AND
$_ -NotLike "*NetFx*" -AND
$_ -NotLike "*Media*" -AND
$_ -NotLike "*NFS*"
}
if ($keepDefender) { $featlist = $featlist | Where-Object { $_ -NotLike "*Defender*" }}
foreach($feature in $featlist)
{
$status = "Removing feature $feature"
Write-Progress -Activity "Removing features" -Status $status -PercentComplete ($counter++/$featlist.Count*100)
Write-Debug "Removing feature $feature"
Disable-WindowsOptionalFeature -Path "$scratchDir" -FeatureName $feature -Remove -ErrorAction SilentlyContinue -NoRestart
}
Write-Progress -Activity "Removing features" -Status "Ready" -Completed
Write-Host "You can re-enable the disabled features at any time, using either Windows Update or the SxS folder in <installation media>\Sources."
}
function Remove-Packages
{
$pkglist = (Get-WindowsPackage -Path "$scratchDir").PackageName
$pkglist = $pkglist | Where-Object {
$_ -NotLike "*ApplicationModel*" -AND
$_ -NotLike "*indows-Client-LanguagePack*" -AND
$_ -NotLike "*LanguageFeatures-Basic*" -AND
$_ -NotLike "*Package_for_ServicingStack*" -AND
$_ -NotLike "*.NET*" -AND
$_ -NotLike "*Store*" -AND
$_ -NotLike "*VCLibs*" -AND
$_ -NotLike "*AAD.BrokerPlugin",
$_ -NotLike "*LockApp*" -AND
$_ -NotLike "*Notepad*" -AND
$_ -NotLike "*immersivecontrolpanel*" -AND
$_ -NotLike "*ContentDeliveryManager*" -AND
$_ -NotLike "*PinningConfirMationDialog*" -AND
$_ -NotLike "*SecHealthUI*" -AND
$_ -NotLike "*SecureAssessmentBrowser*" -AND
$_ -NotLike "*PrintDialog*" -AND
$_ -NotLike "*AssignedAccessLockApp*" -AND
$_ -NotLike "*OOBENetworkConnectionFlow*" -AND
$_ -NotLike "*Apprep.ChxApp*" -AND
$_ -NotLike "*CBS*" -AND
$_ -NotLike "*OOBENetworkCaptivePortal*" -AND
$_ -NotLike "*PeopleExperienceHost*" -AND
$_ -NotLike "*ParentalControls*" -AND
$_ -NotLike "*Win32WebViewHost*" -AND
$_ -NotLike "*InputApp*" -AND
$_ -NotLike "*AccountsControl*" -AND
$_ -NotLike "*AsyncTextService*" -AND
$_ -NotLike "*CapturePicker*" -AND
$_ -NotLike "*CredDialogHost*" -AND
$_ -NotLike "*BioEnrollMent*" -AND
$_ -NotLike "*ShellExperienceHost*" -AND
$_ -NotLike "*DesktopAppInstaller*" -AND
$_ -NotLike "*WebMediaExtensions*" -AND
$_ -NotLike "*WMIC*" -AND
$_ -NotLike "*UI.XaML*"
}
foreach ($pkg in $pkglist)
{
try {
$status = "Removing $pkg"
Write-Progress -Activity "Removing Apps" -Status $status -PercentComplete ($counter++/$pkglist.Count*100)
Remove-WindowsPackage -Path "$scratchDir" -PackageName $pkg -NoRestart -ErrorAction SilentlyContinue
}
catch {
# This can happen if the package that is being removed is a permanent one, like FodMetadata
Write-Host "Could not remove OS package $($pkg)"
continue
}
}
Write-Progress -Activity "Removing Apps" -Status "Ready" -Completed
}
function Remove-ProvisionedPackages([switch] $keepSecurity = $false)
{
<#
.SYNOPSIS
Removes AppX packages from a Windows image during MicroWin processing
.PARAMETER Name
keepSecurity - Boolean that determines whether to keep "Microsoft.SecHealthUI" (Windows Security) in the Windows image
.EXAMPLE
Remove-ProvisionedPackages -keepSecurity:$false
#>
$appxProvisionedPackages = Get-AppxProvisionedPackage -Path "$($scratchDir)" | Where-Object {
$_.PackageName -NotLike "*AppInstaller*" -AND
$_.PackageName -NotLike "*Store*" -and
$_.PackageName -NotLike "*dism*" -and
$_.PackageName -NotLike "*Foundation*" -and
$_.PackageName -NotLike "*FodMetadata*" -and