-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwinutil_cli.ps1
3666 lines (3550 loc) · 112 KB
/
winutil_cli.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 ###
### ###
################################################################################################################
# Compiled at 23.10.05
[CmdletBinding(
SupportsShouldProcess = $true,
ConfirmImpact = 'High',
DefaultParametersetName = 'ListCommand'
)]
Param(
[Parameter(ParameterSetName = 'Tweaks')]
[string[]]$TweakNames,
[Parameter(ParameterSetName = 'Tweaks')]
[string]$DNSProvider,
[Parameter(ParameterSetName = 'Tweaks')]
[string[]]$WindowsFeaturesBundles,
[Parameter(ParameterSetName = 'Tweaks')]
[switch]$Undo,
[Parameter(ParameterSetName = 'ListCommand')]
[switch]$ListTweaks,
[Parameter(ParameterSetName = 'ListCommand')]
[switch]$ListFeatureBundles,
[Parameter(ParameterSetName = 'ListCommand')]
[switch]$ListDNSProviders,
[psobject[]]$ExtraTweaks = @('https://raw.githubusercontent.com/ChrisTitusTech/winutil/main/config/tweaks.json'),
[psobject[]]$ExtraDNSProviders = @('https://raw.githubusercontent.com/ChrisTitusTech/winutil/main/config/dns.json'),
[psobject[]]$ExtraWindowsFeaturesBundles = @('https://raw.githubusercontent.com/ChrisTitusTech/winutil/main/config/feature.json'),
[string]$TranscriptPath = "$ENV:TEMP\Winutil.log",
[switch]$Force
)
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
function Install-Chocolatey {
<#
.SYNOPSIS
Ensures that Chocolatey package manager is installed.
.DESCRIPTION
The Install-Chocolatey function checks if Chocolatey package manager is installed on the system. If it is not installed, the function installs Chocolatey by downloading and executing the installation script from the official Chocolatey website. The function also enables the 'allowGlobalConfirmation' feature of Chocolatey to suppress confirmation prompts during package installations.
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.EXAMPLE
Install-Chocolatey
Checks if Chocolatey is installed and installs it if it is not.
.EXAMPLE
Install-Chocolatey -Force
Installs Chocolatey without prompting for confirmation.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
Param(
[switch]$Force
)
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
try {
# Write-Host "Checking if Chocolatey is Installed..."
$chocoVersion = (Get-Item "$env:ChocolateyInstall\choco.exe" -ErrorAction Ignore).VersionInfo.ProductVersion
if ((Get-Command -Name choco -ErrorAction Ignore) -and $chocoVersion) {
# Write-Host "Chocolatey Already Installed"
return
}
if ($PSCmdlet.ShouldProcess("Installing Chocolatey", "Would you like to install Chocolatey?", "Chocolatey is not installed")) {
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-Error -Message "Couldn't install Chocolatey" -ErrorAction Stop
}
}
function Invoke-ScriptBlock {
<#
.SYNOPSIS
Invokes a script block with the option to confirm before running.
.DESCRIPTION
invokes a script block with the option to confirm before running. It supports the WhatIf and Confirm parameters.
.PARAMETER ScriptBlock
The script block to be invoked.
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.INPUTS
ScriptBlock
.OUTPUTS
ScriptBlock output
.EXAMPLE
Invoke-ScriptBlock -ScriptBlock { Get-ChildItem } -Confirm
This example invokes the Get-ChildItem cmdlet script block with a confirmation prompt.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[scriptblock]$ScriptBlock,
[switch]$Force
)
Begin {
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
}
Process {
if ($PSCmdlet.ShouldProcess($ScriptBlock.ToString(), "Run the script block")) {
return Invoke-Command $scriptblock -ErrorAction Stop
}
}
}
function New-RestorePoint {
<#
.SYNOPSIS
Creates a System Restore Point.
.DESCRIPTION
creates a System Restore Point on the local computer. A System Restore Point is a snapshot of the computer's system files, registry settings, and installed programs at a specific point in time. If the computer experiences problems, you can use System Restore to restore the system to a previous state.
.PARAMETER Description
Specifies a description for the System Restore Point.
.PARAMETER RestorePointType
Specifies the type of restore point. The default is MODIFY_SETTINGS.
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.EXAMPLE
New-RestorePoint -Description "Before installing new software"
Creates a System Restore Point with the description "Before installing new software".
.NOTES
requires administrative privileges to run.
#>
[CmdletBinding(SupportsShouldProcess = $true,
ConfirmImpact = 'Low'
)]
param(
[string]$Description = "System Restore Point",
[ValidateSet(
'APPLICATION_INSTALL',
'APPLICATION_UNINSTALL',
'DEVICE_DRIVER_INSTALL',
'MODIFY_SETTINGS',
'CANCELLED_OPERATION'
)]
[string]$RestorePointType = "MODIFY_SETTINGS",
[switch]$Force
)
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
# Check if the user has administrative privileges
if (!$WhatIfPreference -and -Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "Access denied. Please run as an administrator."
return
}
if ($PSCmdlet.ShouldProcess('Creating a system restore point', 'Are you sure you want to create a system restore point?', 'Create a system restore point')) {
# Check if System Restore is enabled for the main drive
try {
# Try getting restore points to check if System Restore is enabled
Enable-ComputerRestore -Drive "$env:SystemDrive" -ErrorAction Stop -Confirm:$false
}
catch {
Write-Warning "An error occurred while enabling System Restore: $_"
}
# Check if the SystemRestorePointCreationFrequency value exists
$exists = Get-ItemProperty -path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -name "SystemRestorePointCreationFrequency" -ErrorAction SilentlyContinue
if ($null -eq $exists) {
# write-host 'Changing system to allow multiple restore points per day'
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore" -Name "SystemRestorePointCreationFrequency" -Value "0" -Type DWord -Force -ErrorAction Stop | Out-Null
}
Checkpoint-Computer -Description $description -RestorePointType "MODIFY_SETTINGS"
# Write-Host -ForegroundColor Green "System Restore Point Created Successfully"
}
}
# }
function Remove-AppxPackageLike {
<#
.SYNOPSIS
removes any APPX packages containing 'Name'.
.DESCRIPTION
The Remove-AppxPackageLike function removes any APPX packages containing 'Name'. It removes both the installed package and the provisioned package.
.PARAMETER Name
Specifies the name of the APPX package to remove.
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.EXAMPLE
Remove-AppxPackageLike -Name "Microsoft.Microsoft3DViewer"
This example removes the "Microsoft.Microsoft3DViewer" APPX package.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
# [WildcardPattern]
[string]$Name,
[switch]$Force
)
Begin {
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
}
Process {
$Name = "*$Name*"
# Check if the user has administrative privileges
if (!$WhatIfPreference -and -Not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "The requested operation requires elevation. Please run as an administrator." # Get-AppxProvisionedPackage requires elevation
return
}
try {
$appxPackages = Get-AppxPackage $Name
$appxProvisionedPackages = Get-AppxProvisionedPackage -Online | Where-Object DisplayName -like $Name
}
Catch [System.Exception] {
# We shouldn't be able to get to here
if ($psitem.Exception.Message -like "*The requested operation requires elevation*") {
Write-Warning "Unable to uninstall $name due to a Security Exception"
}
Else {
Write-Warning "Unable to uninstall $name due to unhandled exception"
Write-Warning $psitem.Exception.StackTrace
}
}
Catch {
Write-Warning "Unable to uninstall $name due to unhandled exception"
Write-Warning $psitem.Exception.StackTrace
}
$packages = $($appxPackages | ForEach-Object { $_.Name } ; $appxProvisionedPackages | ForEach-Object { $_.DisplayName }) | Sort-Object | Get-Unique
if ($packages.Count -eq 0) {
Write-Error "No packages found matching pattern $Name"
return
}
$packages = ($packages -join ", ").trim()
Try {
if ($PSCmdlet.ShouldProcess($packages)) {
$appxPackages | Remove-AppxPackage -ErrorAction Continue
$appxProvisionedPackages | Remove-AppxProvisionedPackage -Online -ErrorAction Continue
}
}
Catch [System.Exception] {
if ($psitem.Exception.Message -like "*The requested operation requires elevation*") {
Write-Warning "Unable to uninstall $name due to a Security Exception"
}
Else {
Write-Warning "Unable to uninstall $name due to unhandled exception"
Write-Warning $psitem.Exception.StackTrace
}
}
Catch {
Write-Warning "Unable to uninstall $name due to unhandled exception"
Write-Warning $psitem.Exception.StackTrace
}
}
}
function Test-RegistryKeyValueType {
<#
.SYNOPSIS
Tests if a registry key exists and, if provided a registry value, tests the value and type of a registry value matching.
.DESCRIPTION
The Test-RegistryKeyValueType function tests if a registry key exists. If a registry value is provided, it tests the value and type of a registry value matching.
.PARAMETER Path
Specifies the path to the registry key.
.PARAMETER Name
Specifies the name of the registry value.
.PARAMETER Type
Specifies the type of the registry value.
.PARAMETER Value
Specifies the value to compare against. Pass integer, string, or PowerShell array.
.EXAMPLE
Test-RegistryKeyValueType -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name "ProductName" -Type String -Value "Windows 10 Enterprise"
This example tests if the registry key "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" exists and if the value of the "ProductName" registry value is "Windows 10 Enterprise".
#>
[CmdletBinding(DefaultParametersetName = 'None')]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(ParameterSetName = 'NameValueType', Mandatory = $true)]
[string]$Name,
[Parameter(ParameterSetName = 'NameValueType', Mandatory = $true)]
[Microsoft.Win32.RegistryValueKind]$Type,
[Parameter(ParameterSetName = 'NameValueType', Mandatory = $true, HelpMessage = 'The value to compare against, Pass integer, string or powershell array.')]
$Value
)
try {
$RegistryKey = Get-Item -Path $Path -ErrorAction Stop
switch ($PsCmdlet.ParameterSetName) {
'NameValueType' {
$RegistryKeyValueKind = $RegistryKey.GetValueKind($Name)
$RegistryKeyValue = $RegistryKey.GetValue($Name)
if ($RegistryKeyValueKind -eq $Type) {
if (!$(Compare-Object $RegistryKeyValue $Value)) {
return $true
}
}
}
default {
return $true
}
}
}
catch {
if ($PSItem.Exception.Message -like "*Cannot find path*") {
}
if ($PSItem.Exception.Message -like '*does not exist*') {
}
else {
throw $PSItem
}
}
return $false
}
function Set-RegistryKey {
<#
.SYNOPSIS
Sets a registry key value.
.DESCRIPTION
The Set-RegistryKey function sets a registry key value with the specified name, type, and value. If the key does not exist, it is created.
.PARAMETER Path
The path to the registry key.
.PARAMETER Name
The name of the registry value.
.PARAMETER Type
The type of the registry value.
.PARAMETER Value
The value to set.
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.EXAMPLE
Set-RegistryKey -Path "HKLM:\SOFTWARE\MyApp" -Name "MySetting" -Type String -Value "Hello, World!"
This example sets the value of the "MySetting" registry value under the "HKLM:\SOFTWARE\MyApp" key to "Hello, World!".
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[Parameter(Mandatory = $true)]
[string]$Name,
[Parameter(Mandatory = $true)]
[Microsoft.Win32.RegistryValueKind]$Type,
[Parameter(Mandatory = $true)]
$Value,
[switch]$Force
)
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
if ((Test-RegistryKeyValueType -Path $Path -Name $Name -Type $Type -Value $Value -ErrorAction SilentlyContinue)) {
return
}
if ($PSCmdlet.ShouldProcess("$Path", "Set Registry Key Value: '$Name' to value: '$Value'")) {
if (!(Test-Path 'HKU:\')) { New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS }
if (!(Test-Path $Path)) {
New-Item -Path $Path -Force -ErrorAction Stop | Out-Null
}
Set-ItemProperty -Path $Path -Name $Name -Type $Type -Value $Value -Force -ErrorAction Stop | Out-Null
}
}
function Set-ScheduledTaskState {
<#
.SYNOPSIS
Enables or disables the provided Scheduled Task.
.DESCRIPTION
The Set-WinUtilScheduledTask function enables or disables the provided Scheduled Task. takes two parameters: the name of the Scheduled Task and the desired state (either "Enabled" or "Disabled").
.PARAMETER TaskName
The name of the Scheduled Task to enable or disable.
.PARAMETER State
The desired state of the Scheduled Task. Valid values are "Enabled" and "Disabled".
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.EXAMPLE
Set-WinUtilScheduledTask -TaskName "Microsoft\Windows\Application Experience\Microsoft Compatibility Appraiser" -State "Disabled"
Disables the "Microsoft Compatibility Appraiser" Scheduled Task.
.NOTES
Could require administrative privileges to run.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$TaskName,
[Parameter(Mandatory = $true)]
[ValidateSet("Enabled", "Disabled")]
$State,
[switch]$Force
)
Begin {
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
}
Process {
if ($PSCmdlet.ShouldProcess($TaskName, "$($State.Substring(0,$State.length-1)) ScheduledTask")) {
Try {
if ($State -eq "Disabled") {
# Write-Host "Disabling Scheduled Task $TaskName"
Disable-ScheduledTask -TaskName $TaskName -ErrorAction Stop
}
if ($State -eq "Enabled") {
# Write-Host "Enabling Scheduled Task $TaskName"
Enable-ScheduledTask -TaskName $TaskName -ErrorAction Stop
}
}
Catch [System.Exception] {
if ($psitem.Exception.Message -like "*The system cannot find the file specified*") {
Write-Error "Scheduled Task $TaskName was not Found"
return
}
Else {
throw $psitem
}
}
}
}
}
Function Set-ServicesStartupType {
<#
.SYNOPSIS
Sets the startup type of a Windows service.
.DESCRIPTION
The Set-ServicesStartupType function sets the startup type of a Windows service to Automatic, Manual, or Disabled.
.PARAMETER Name
Specifies the search name of services to set the startup type for.
.PARAMETER StartupType
Specifies the startup type to set for the service. Valid values are Automatic, Manual, and Disabled.
.PARAMETER Force
Forces the command to run without prompting for confirmation.
.EXAMPLE
Set-ServicesStartupType -Name "Spooler" -StartupType "Disabled"
Sets the startup type of the Spooler service to Disabled.
.EXAMPLE
Set-ServicesStartupType -Name "Lan*" -StartupType "Disabled"
Sets the startup type of all services starting with "Lan" to Disabled.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
# [WildcardPattern]
$Name,
[Parameter(Mandatory = $true)]
[System.ServiceProcess.ServiceStartMode]$StartupType, #powershell 5.1 compatibility, AutomaticDelayedStart is not supported
[switch]$Force
)
Begin {
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
}
Process {
# Check if the service exists
try {
$services = Get-Service -Name $Name -ErrorAction Stop
if ($services.Count -eq 0) {
Write-Error "No services found matching name $Name"
return
}
$Names = ($services -join ", ").trim()
if ($PSCmdlet.ShouldProcess($Names, "Set Services StartupType to $StartupType")) {
$services | Set-Service -StartupType $StartupType -ErrorAction Stop
}
}
catch {
Write-Error $PSItem
}
}
}
function Install-WinUtilWindowsFeaturesBundle {
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
$WindowsFeaturesBundle,
[Parameter(Mandatory = $true)]
$bundles
)
Begin {
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
}
Process {
if ($PSCmdlet.ShouldProcess($WindowsFeaturesBundle, 'Install Windows Feature Bundle')) {
$WindowsFeaturesBundle | ForEach-Object {
if ($bundles.$psitem.feature) {
Foreach ($feature in $bundles.$psitem.feature ) {
Enable-WindowsOptionalFeature -Online -FeatureName $feature -All -NoRestart
}
}
if ($bundles.$psitem.InvokeScript) {
Foreach ( $script in $bundles.$psitem.InvokeScript ) {
$Scriptblock = [scriptblock]::Create($script)
Invoke-ScriptBlock $scriptblock -ErrorAction stop -Confirm:$false
}
}
}
}
}
}
function Invoke-WinUtil {
# TODO: add support for confrim and whatif
Param(
[Parameter(Mandatory = $false)]
[string[]]$TweakNames,
[Parameter(Mandatory = $false)]
[string]$DNSProvider,
[Parameter(Mandatory = $false)]
[string[]]$WindowsFeaturesBundles,
[Parameter(Mandatory = $false)]
$dns,
$tweaks,
$feature,
[switch]$Undo
)
$DNSProvider = $DNSProvider.trim()
if ($TweakNames.count -eq 0 -and $WindowsFeaturesBundles.count -eq 0 -and !$DNSProvider) {
throw "You must specify at least one tweak, feature bundle, or DNS provider."
return
}
if ($TweakNames -or $WindowsFeaturesBundles) {
New-RestorePoint
}
if ($DNSProvider) {
Set-WinUtilDNSProvider -DNSProvider $DNSProvider -dns $dns
}
if ($TweakNames) {
$TweakNames | Invoke-WinUtilTweak -Tweaks $tweaks -Undo:$undo
}
if ($WindowsFeaturesBundles) {
$WindowsFeaturesBundles | Install-WinUtilWindowsFeaturesBundle -bundles $feature
}
}
function Invoke-WinUtilTweak {
<#
.SYNOPSIS
Applies or undoes Windows utility tweaks.
.DESCRIPTION
applies or undoes Windows utility tweaks based on the specified tweak name(s).
.PARAMETER TweakName
Specifies the name(s) of the tweak(s) to apply or undo.
.PARAMETER Undo
Indicates whether to undo the specified tweak(s).
.PARAMETER Tweaks
Specifies the tweaks available to apply or undo.
.PARAMETER Force
Indicates whether to force the operation without prompting for confirmation.
.EXAMPLE
Invoke-WinUtilTweaks -TweakName "Disable Cortana", "Disable Telemetry" -Tweaks $Tweaks
This example applies the "Disable Cortana" and "Disable Telemetry" tweaks.
.EXAMPLE
Invoke-WinUtilTweaks -TweakName "Disable Cortana" -Undo -Tweaks $Tweaks
This example undoes the "Disable Cortana" tweak.
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$TweakName,
[Parameter(Mandatory = $false)]
[switch]$Undo,
[Parameter(Mandatory = $true)]
$Tweaks,
[switch]$Force
)
Begin {
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
if ($Undo) {
$Values = @{
Registry = "OriginalValue"
ScheduledTask = "OriginalState"
Service = "OriginalType"
ScriptType = "UndoScript"
}
}
Else {
$Values = @{
Registry = "Value"
ScheduledTask = "State"
Service = "StartupType"
ScriptType = "InvokeScript"
}
}
}
Process {
if ($PSCmdlet.ShouldProcess($TweakName, "$(&{If(!$Undo) {"Apply"} Else {"Undo"}}) Tweak")) {
if ($Tweaks.$TweakName.ScheduledTask) {
$Tweaks.$TweakName.ScheduledTask | ForEach-Object {
Set-ScheduledTaskState -TaskName $psitem.Name -State $psitem.$($values.ScheduledTask) -Confirm:$false
}
}
if ($Tweaks.$TweakName.service) {
$Tweaks.$TweakName.service | ForEach-Object {
Set-ServicesStartupType -Name $psitem.Name -StartupType $psitem.$($values.Service) -Confirm:$false
}
}
if ($Tweaks.$TweakName.registry) {
$Tweaks.$TweakName.registry | ForEach-Object {
Set-RegistryKey -Name $psitem.Name -Path $psitem.Path -Type $psitem.Type -Value $psitem.$($values.registry) -Confirm:$false
}
}
if ($Tweaks.$TweakName.$($values.ScriptType)) {
$Tweaks.$TweakName.$($values.ScriptType) | ForEach-Object {
$Scriptblock = [scriptblock]::Create($psitem)
Invoke-ScriptBlock -ScriptBlock $scriptblock -Confirm:$false
}
}
if (!$Undo) {
if ($Tweaks.$TweakName.appx) {
$Tweaks.$TweakName.appx | ForEach-Object {
Remove-AppxPackageLike -Name $psitem -Confirm:$false
}
}
}
}
}
}
Function Merge-Hashtables([ScriptBlock]$Operator) {
# https://stackoverflow.com/a/32890418/12603110
$Output = @{}
ForEach ($Hashtable in $Input) {
If ($Hashtable -is [Hashtable]) {
ForEach ($Key in $Hashtable.Keys) { $Output.$Key = If ($Output.ContainsKey($Key)) { @($Output.$Key) + $Hashtable.$Key } Else { $Hashtable.$Key } }
}
}
If ($Operator) { ForEach ($Key in @($Output.Keys)) { $_ = @($Output.$Key); $Output.$Key = Invoke-Command $Operator } }
$Output
}
Function Merge-CustomObjects([ScriptBlock]$Operator) {
$Output = [PSCustomObject]@{}
ForEach ($Hashtable in $Input) {
If ($Hashtable -is [PSCustomObject]) {
ForEach ($Key in (Get-Member -InputObject $Hashtable -MemberType NoteProperty).Name) {
Add-Member -Force -InputObject $Output -MemberType NoteProperty -Name $Key -Value $(if ($Output.psobject.properties.match($Key).Count) { @($Output.$Key) + $Hashtable.$Key } Else { $Hashtable.$Key })
}
}
}
If ($Operator) { ForEach ($Key in @(Get-Member -InputObject $Output -MemberType NoteProperty).Name) { $_ = @($Output.$Key); $Output.$Key = Invoke-Command $Operator } }
$Output
}
function Set-WinUtilDNSProvider {
<#
.DESCRIPTION
will set the DNS of all interfaces that are in the "Up" state. It will lookup the values from the DNS.Json file
.EXAMPLE
Set-WinUtilDNS -DNSProvider "google"
#>
[CmdletBinding(
SupportsShouldProcess,
ConfirmImpact = 'High'
)]
param(
[Parameter(Mandatory = $true)]
[string]$DNSProvider,
$dns,
[switch]$Force
)
if ($Force -and -not $Confirm) {
$ConfirmPreference = 'None'
}
if (!$dns.$DNSProvider.Primary) {
Write-Error "DNSProvider $DNSProvider not found"
return
}
if ($PSCmdlet.ShouldProcess($DNSProvider, 'Set DNS provider')) {
Try {
$Adapters = Get-NetAdapter | Where-Object { $_.Status -eq "Up" }
# Write-Host "Ensuring DNS is set to $DNSProvider on the following interfaces"
# Write-Host $($Adapters | Out-String)
Foreach ($Adapter in $Adapters) {
if ($DNSProvider -eq "DHCP") {
Set-DnsClientServerAddress -InterfaceIndex $Adapter.ifIndex -ResetServerAddresses
}
Else {
Set-DnsClientServerAddress -InterfaceIndex $Adapter.ifIndex -ServerAddresses ("$($dns.$DNSProvider.Primary)", "$($dns.$DNSProvider.Secondary)")
}
}
}
Catch {
Write-Error $PSItem
}
}
}
$dns = '{
"Google":{
"Primary": "8.8.8.8",
"Secondary": "8.8.4.4"
},
"Cloudflare":{
"Primary": "1.1.1.1",
"Secondary": "1.0.0.1"
},
"Cloudflare_Malware":{
"Primary": "1.1.1.2",
"Secondary": "1.0.0.2"
},
"Cloudflare_Malware_Adult":{
"Primary": "1.1.1.3",
"Secondary": "1.0.0.3"
},
"Level3":{
"Primary": "4.2.2.2",
"Secondary": "4.2.2.1"
},
"Open_DNS":{
"Primary": "208.67.222.222",
"Secondary": "208.67.220.220"
},
"Quad9":{
"Primary": "9.9.9.9",
"Secondary": "149.112.112.112"
}
}'
$dnsschema = '{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"Primary": {
"type": "string",
"format": "ipv4"
},
"Secondary": {
"type": "string",
"format": "ipv4"
}
},
"required": [
"Primary",
"Secondary"
]
}
}'
$feature = '{
"WPFFeaturesdotnet": {
"feature": [
"NetFx4-AdvSrvs",
"NetFx3"
],
"InvokeScript": [
]
},
"WPFFeatureshyperv": {
"feature": [
"HypervisorPlatform",
"Microsoft-Hyper-V-All",
"Microsoft-Hyper-V",
"Microsoft-Hyper-V-Tools-All",
"Microsoft-Hyper-V-Management-PowerShell",
"Microsoft-Hyper-V-Hypervisor",
"Microsoft-Hyper-V-Services",
"Microsoft-Hyper-V-Management-Clients"
],
"InvokeScript": [
"Start-Process -FilePath cmd.exe -ArgumentList ''/c bcdedit /set hypervisorschedulertype classic'' -Wait"
]
},
"WPFFeatureslegacymedia": {
"feature": [
"WindowsMediaPlayer",
"MediaPlayback",
"DirectPlay",
"LegacyComponents"
],
"InvokeScript": [
]
},
"WPFFeaturewsl": {
"feature": [
"VirtualMachinePlatform",
"Microsoft-Windows-Subsystem-Linux"
],
"InvokeScript": [
]
},
"WPFFeaturenfs": {
"feature": [
"ServicesForNFS-ClientOnly",
"ClientForNFS-Infrastructure",
"NFS-Administration"
],
"InvokeScript": [
"nfsadmin client stop
Set-ItemProperty -Path ''HKLM:\\SOFTWARE\\Microsoft\\ClientForNFS\\CurrentVersion\\Default'' -Name ''AnonymousUID'' -Type DWord -Value 0
Set-ItemProperty -Path ''HKLM:\\SOFTWARE\\Microsoft\\ClientForNFS\\CurrentVersion\\Default'' -Name ''AnonymousGID'' -Type DWord -Value 0
nfsadmin client start
nfsadmin client localhost config fileaccess=755 SecFlavors=+sys -krb5 -krb5i
"
]
}
}'
$featureschema = '{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"feature": {
"type": "array",
"items": {
"type": "string"
}
},
"InvokeScript": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": ["feature", "InvokeScript"]
}
}'
$tweaks = '{
"WPFEssTweaksAH": {
"registry": [
{
"Path": "HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows\\System",
"Name": "EnableActivityFeed",
"Type": "DWord",
"Value": "0",
"OriginalValue": "1"
},
{
"Path": "HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows\\System",
"Name": "PublishUserActivities",
"Type": "DWord",
"Value": "0",
"OriginalValue": "1"
},
{
"Path": "HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows\\System",
"Name": "UploadUserActivities",
"Type": "DWord",
"Value": "0",
"OriginalValue": "1"
}
]
},
"WPFEssTweaksHiber": {
"registry": [
{
"Path": "HKLM:\\System\\CurrentControlSet\\Control\\Session Manager\\Power",
"Name": "HibernateEnabled",
"Type": "DWord",
"Value": "0",
"OriginalValue": "1"
},
{
"Path": "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FlyoutMenuSettings",
"Name": "ShowHibernateOption",
"Type": "DWord",
"Value": "0",
"OriginalValue": "1"
}
],
"InvokeScript": [
"powercfg.exe /hibernate off"
]
},
"WPFEssTweaksHome": {
"service": [
{
"Name": "HomeGroupListener",
"StartupType": "Manual",
"OriginalType": "Automatic"
},
{
"Name": "HomeGroupProvider",
"StartupType": "Manual",
"OriginalType": "Automatic"
}
]
},
"WPFEssTweaksLoc": {
"registry": [
{
"Path": "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\CapabilityAccessManager\\ConsentStore\\location",
"Name": "Value",
"Type": "String",
"Value": "Deny",
"OriginalValue": "Allow"
},
{
"Path": "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Sensor\\Overrides\\{BFA794E4-F964-4FDB-90F6-51056BFE4B44}",
"Name": "SensorPermissionState",
"Type": "DWord",
"Value": "0",
"OriginalValue": "1"
},
{
"Path": "HKLM:\\SYSTEM\\CurrentControlSet\\Services\\lfsvc\\Service\\Configuration",
"Name": "Status",
"Type": "DWord",
"Value": "0",