forked from ChrisTitusTech/winutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runspace.ps1
1529 lines (1186 loc) · 62.3 KB
/
runspace.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
#for CI/CD
$BranchToUse = 'main'
<#
.NOTES
Author : @ChrisTitusTech
Runspace Author : @DeveloperDurp
Version 0.1
#>
#region Variables
$sync = [Hashtable]::Synchronized(@{})
$sync.logfile = "$env:TEMP\winutil.log"
$sync.taskrunning = $false
$sync.taskmessage = "There is currently a task running. Please try again once previous task is complete."
$sync.tasktitle = "Task in progress"
$VerbosePreference = "Continue"
if(!$env:args){$gui = $true}
#endregion Variables
#region Functions
#===========================================================================
# Button clicks
#===========================================================================
function Invoke-Button {
<#
.DESCRIPTION
Meant to make creating buttons easier. There is a section below in the gui that will assign this function to every button.
This way you can dictate what each button does from this function.
Input will be the name of the button that is clicked.
#>
Param ([string]$Button)
#Use this to get the name of the button
#[System.Windows.MessageBox]::Show("$Button","Chris Titus Tech's Windows Utility","OK","Info")
Switch -Wildcard ($Button){
"*Tab*BT*" {switchtab $Button}
"*InstallUpgrade*" {Invoke-command $sync.GUIInstallPrograms -ArgumentList "Upgrade"}
"*desktop*" {Tweak-Buttons $Button}
"*laptop*" {Tweak-Buttons $Button}
"*minimal*" {Tweak-Buttons $Button}
"*undoall*" {Invoke-command $Sync.GUIUndoTweaks}
"install" {Invoke-command $sync.GUIInstallPrograms -ArgumentList "$(uncheckall "Install")"}
"tweaksbutton" {Invoke-command $Sync.GUITweaks -ArgumentList "$(uncheckall "tweaks")"}
"FeatureInstall" {Invoke-command $Sync.GUIFeatures -ArgumentList "$(uncheckall "feature")"}
"Panelcontrol" {cmd /c control}
"Panelnetwork" {cmd /c ncpa.cpl}
"Panelpower" {cmd /c powercfg.cpl}
"Panelsound" {cmd /c mmsys.cpl}
"Panelsystem" {cmd /c sysdm.cpl}
"Paneluser" {cmd /c "control userpasswords2"}
"Updates*" {Invoke-command $sync.GUIUpdates -ArgumentList "$button"}
"FixesUpdate" {Invoke-command $sync.GUIUpdates -ArgumentList "$button"}
"*AutoLogin" {Invoke-Runspace $Sync.AutologinInstall}
"DisableDarkMode" {Invoke-Runspace $Sync.DarkModeToggle -ArgumentList "$False"}
"EnableDarkMode" {Invoke-Runspace $Sync.DarkModeToggle -ArgumentList "$True"}
"PanelDISM" {
Start-Process PowerShell -ArgumentList "Write-Host '(1/4) Chkdsk' -ForegroundColor Green; Chkdsk /scan;
Write-Host '`n(2/4) SFC - 1st scan' -ForegroundColor Green; sfc /scannow;
Write-Host '`n(3/4) DISM' -ForegroundColor Green; DISM /Online /Cleanup-Image /Restorehealth;
Write-Host '`n(4/4) SFC - 2nd scan' -ForegroundColor Green; sfc /scannow;
Read-Host '`nPress Enter to Continue'" -verb runas
}
}
}
function uncheckall {
<#
.DESCRIPTION
Function is meant to find all checkboxes that are checked on the specefic tab and input them into a script.
Outputed data will be the names of the checkboxes comma seperated.
"Installadvancedip,Installbitwarden"
.EXAMPLE
uncheckall "Install"
#>
param($group)
if ($sync.taskrunning -eq $true){
return
}
$sync.keys | Where-Object {$psitem -like "*$($group)?*" `
-and $psitem -notlike "$($group)Install" `
-and $psitem -notlike "*GUI*" `
-and $psitem -notlike "*Script*"
} | ForEach-Object {
if ($sync["$psitem"].IsChecked -eq $true){
$output += ",$psitem"
$sync["$psitem"].IsChecked = $false
}
}
if($output){Write-Output $output.Substring(1)}
}
function Invoke-Runspace {
<#
.DESCRIPTION
Simple function to make it easier to invoke a runspace from inside the script.
.EXAMPLE
$params = @{
ScriptBlock = $sync.ScriptsInstallPrograms
ArgumentList = "Installadvancedip,Installbitwarden"
Verbose = $true
}
Invoke-Runspace @params
#>
[CmdletBinding()]
Param (
$ScriptBlock,
$ArgumentList
)
$Script = [PowerShell]::Create().AddScript($ScriptBlock).AddArgument($ArgumentList)
$Script.Runspace = $runspace
$Script.BeginInvoke()
}
#===========================================================================
# Navigation Controls
#===========================================================================
function switchtab {
<#
.DESCRIPTION
Sole purpose of this fuction reduce duplicated code for switching between tabs.
#>
Param ($button)
$x = [int]($button -replace "Tab","" -replace "BT","") - 1
0..3 | ForEach-Object {
if ($x -eq $psitem){$sync["TabNav"].Items[$psitem].IsSelected = $true}
else{$sync["TabNav"].Items[$psitem].IsSelected = $false}
}
}
Function Tweak-Buttons {
<#
.DESCRIPTION
Meant to make settings presets easier in the tweaks tab. Will pull the data from config/preset.json
#>
Param ($button)
$preset = $sync.preset.$button
$sync.keys | Where-Object {$psitem -like "*tweaks?*" -and $psitem -notlike "tweaksbutton"} | ForEach-Object {
if ($preset -contains $psitem ){$sync["$psitem"].IsChecked = $True}
Else{$sync["$psitem"].IsChecked = $false}
}
}
#endregion Functions
#===========================================================================
# Scritps to be ran inside a runspace
#===========================================================================
#region Scripts
#===========================================================================
# Generic Scripts
#===========================================================================
$sync.WriteLogs = {
<#
.DESCRIPTION
Simple function to write logs to a temp directory.
.EXAMPLE
$Level = "INFO"
$Message = "This is a test message!"
$LogPath = "$ENV:TEMP\winutil.log"
Invoke-command $sync.WriteLogs -ArgumentList ($Level,$Message,$LogPath)
#>
[cmdletbinding()]
param(
$Level = "Info",
$Message,
$LogPath = "$env:TEMP\winutil.log"
)
$date = get-date
$delimiter = '|'
write-output "$date $delimiter $Level $delimiter $message" | out-file -Append -Encoding ascii -FilePath $LogPath
if($Level -eq "ERROR" -or $Level -eq "FAILURE"){
write-Error "$date $delimiter $Level $delimiter $message"
return
}
if($Level -eq "Warning"){
Write-Warning "$date $delimiter $Level $delimiter $message"
return
}
Write-Verbose "$date $delimiter $Level $delimiter $message"
}
$Sync.AutologinInstall = {
# Official Microsoft recommendation https://learn.microsoft.com/en-us/sysinternals/downloads/autologon
Invoke-WebRequest "https://live.sysinternals.com/Autologon.exe" -OutFile $env:TEMP\autologin.exe
Start-Process -FilePath powershell.exe -Verb runas -ArgumentList "-c $ENV:Temp\autologin.exe" -WindowStyle Hidden
}
$Sync.DarkModeToggle = {
param($enabled)
$Theme = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize"
if($enabled -eq $True){
Set-ItemProperty $Theme AppsUseLightTheme -Value 0
Invoke-command $sync.WriteLogs -ArgumentList ("INFO","Dark Mode has been enabled",$sync.logfile)
}
if($enabled -eq $False){
Set-ItemProperty $Theme AppsUseLightTheme -Value 1
Invoke-command $sync.WriteLogs -ArgumentList ("INFO","Dark Mode has been disabled",$sync.logfile)
}
}
#===========================================================================
# Install Tab
#===========================================================================
<#
This section is working as expected and logs output to console and $ENV:Temp\winutil.log
TODO: Error Handling with winget. Currently it does not handle errors as expected.
#>
$Sync.GUIInstallPrograms = {
<#
.DESCRIPTION
This Scriptblock is meant to be ran from inside the GUI and will prevent the user from starting another install task.
Input data will look like below and link with the name of the check box. This will then look to the config/applications.json file to find
the winget install commands for the selected applications.
Installadvancedip,Installbitwarden
.EXAMPLE
Invoke-command $sync.GUIInstallPrograms -ArgumentList "Installadvancedip,Installbitwarden"
#>
Param ($programstoinstall)
#Check if any check boxes have been checked and if a task is currently running
if ($sync.taskrunning -eq $true){
[System.Windows.MessageBox]::Show($sync.taskmessage,$sync.tasktitle,"OK","Info")
return
}
if($programstoinstall -notlike "*install*"){
[System.Windows.MessageBox]::Show("Please check the applications you wish to install",'Nothing to do',"OK","Info")
return
}
#Section to see if winget will upgrade all installs or which winget commands to run from config/applications.json
$programstoinstall = $programstoinstall -split ","
if($programstoinstall -eq "Upgrade"){
$winget = ",Upgrade"
}
else{
foreach ($program in $programstoinstall){
$($sync.applications.install.$("WPF" + $program).winget) -split ";" | ForEach-Object {
if($psitem){
$winget += ",$psitem"
}Else{
Invoke-command $sync.WriteLogs -ArgumentList ("WARNING","$Program Not found")
}
}
}
}
if($winget -eq $null){
[System.Windows.MessageBox]::Show("No found applications to install",'Nothing to do',"OK","Info")
return
}
#Invoke a runspace so that the GUI does not lock up
$sync.taskrunning = $true
$params = @{
ScriptBlock = $sync.ScriptsInstallPrograms
ArgumentList = "$($winget.substring(1))"
Verbose = $true
}
Invoke-Runspace @params
}
$sync.ScriptsInstallPrograms = {
<#
.DESCRIPTION
This scriptblock will detect if winget is installed and if not attempt to install it. Once ready it will then either upgrade any installs or attempt to install any applications provided.
.EXAMPLE
$params = @{
ScriptBlock = $sync.ScriptsInstallPrograms
ArgumentList = "git.git,WinDirStat.WinDirStat"
}
VerbosePreference = "Continue"
Invoke-Command @params
.EXAMPLE
$params = @{
ScriptBlock = $sync.ScriptsInstallPrograms
ArgumentList = "Upgrade"
}
VerbosePreference = "Continue"
Invoke-Command @params
#>
Param ($programstoinstall)
$programstoinstall = $programstoinstall -split ","
function Write-Logs {
param($Level, $Message, $LogPath)
Invoke-command $sync.WriteLogs -ArgumentList ($Level,$Message,$LogPath)
}
#region Check for WinGet and install if not present
if (Test-Path $env:userprofile\AppData\Local\Microsoft\WindowsApps\winget.exe) {
#Checks if winget executable exists and if the Windows Version is 1809 or higher
Write-Logs -Level INFO -Message "WinGet was detected" -LogPath $sync.logfile
}
else {
if (($sync.ComputerInfo.WindowsVersion) -lt "1809") {
#Checks if Windows Version is too old for winget
Write-Logs -Level Warning -Message "Winget is not supported on this version of Windows (Pre-1809). Stopping installs" -LogPath $sync.logfile
return
}
Write-Logs -Level INFO -Message "WinGet was not detected" -LogPath $sync.logfile
if (((($sync.ComputerInfo.OSName.IndexOf("LTSC")) -ne -1) -or ($sync.ComputerInfo.OSName.IndexOf("Server") -ne -1)) -and (($sync.ComputerInfo.WindowsVersion) -ge "1809")) {
Try{
#Checks if Windows edition is LTSC/Server 2019+
#Manually Installing Winget
Write-Logs -Level INFO -Message "LTSC/Server Edition detected. Running Alternative Installer" -LogPath $sync.logfile
#Download Needed Files
$step = "Downloading the required files"
Write-Logs -Level INFO -Message $step -LogPath $sync.logfile
Start-BitsTransfer -Source "https://aka.ms/Microsoft.VCLibs.x64.14.00.Desktop.appx" -Destination "$ENV:TEMP\Microsoft.VCLibs.x64.14.00.Desktop.appx" -ErrorAction Stop
Start-BitsTransfer -Source "https://github.com/microsoft/winget-cli/releases/download/v1.2.10271/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Destination "$ENV:TEMP/Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -ErrorAction Stop
Start-BitsTransfer -Source "https://github.com/microsoft/winget-cli/releases/download/v1.2.10271/b0a0692da1034339b76dce1c298a1e42_License1.xml" -Destination "$ENV:TEMP/b0a0692da1034339b76dce1c298a1e42_License1.xml" -ErrorAction Stop
#Installing Packages
$step = "Installing Packages"
Write-Logs -Level INFO -Message $step -LogPath $sync.logfile
Add-AppxProvisionedPackage -Online -PackagePath "$ENV:TEMP\Microsoft.VCLibs.x64.14.00.Desktop.appx" -SkipLicense -ErrorAction Stop
Add-AppxProvisionedPackage -Online -PackagePath "$ENV:TEMP\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -LicensePath "$ENV:TEMP\b0a0692da1034339b76dce1c298a1e42_License1.xml" -ErrorAction Stop
#Sleep for 5 seconds to maximize chance that winget will work without reboot
Start-Sleep -s 5
#Removing no longer needed Files
$step = "Removing Files"
Write-Logs -Level INFO -Message $step -LogPath $sync.logfile
Remove-Item -Path "$ENV:TEMP\Microsoft.VCLibs.x64.14.00.Desktop.appx" -Force
Remove-Item -Path "$ENV:TEMP\Microsoft.DesktopAppInstaller_8wekyb3d8bbwe.msixbundle" -Force
Remove-Item -Path "$ENV:TEMP\b0a0692da1034339b76dce1c298a1e42_License1.xml" -Force
$step = "WinGet Sucessfully installed"
Write-Logs -Level INFO -Message $step -LogPath $sync.logfile
}Catch{Write-Logs -Level FAILURE -Message "WinGet Install failed at $step" -LogPath $sync.logfile}
}
else {
Try{
#Installing Winget from the Microsoft Store
$step = "Installing WinGet"
Write-Logs -Level INFO -Message $step -LogPath $sync.logfile
Start-Process "ms-appinstaller:?source=https://aka.ms/getwinget"
$nid = (Get-Process AppInstaller).Id
Wait-Process -Id $nid
$step = "Winget Installed"
Write-Logs -Level INFO -Message $step -LogPath $sync.logfile
}Catch{Write-Logs -Level FAILURE -Message "WinGet Install failed at $step" -LogPath $sync.logfile}
}
Write-Logs -Level INFO -Message "WinGet has been installed" -LogPath $sync.logfile
Start-Sleep -Seconds 15
}
#endregion Check for WinGet and install if not present
$results = @()
foreach ($program in $programstoinstall){
if($programstoinstall -eq "Upgrade"){
$Message = "Attempting to upgrade packages"
$ErrorMessage = "Failed to upgrade packages"
$SuccessMessage = "Upgardes have completed"
$ArgumentList = "upgrade --all"
}
else{
$Message = "$($program) was selected to be installed."
$ErrorMessage = "$($program) failed to installed."
$SuccessMessage = "$($program) has been installed"
$ArgumentList = "install -e --accept-source-agreements --accept-package-agreements --silent $($program)"
}
try {
Write-Logs -Level INFO -Message "$Message" -LogPath $sync.logfile
Write-Host ""
$installs = Start-Process -FilePath winget -ArgumentList $ArgumentList -ErrorAction Stop -Wait -PassThru -NoNewWindow
}
catch {
Write-Logs -Level FAILURE -Message $ErrorMessage -LogPath $sync.logfile
$results += $program
}
}
Write-Logs -Level INFO -Message "Installs have completed" -LogPath $sync.logfile
if($sync["Form"]){
$sync.taskrunning = $false
[System.Windows.MessageBox]::Show("All applications have been installed",'Installs are done!',"OK","Info")
}
}
#===========================================================================
# Tab 2 - Tweaks Buttons
#===========================================================================
<#
This section is working as expected and logs output to console and $ENV:Temp\winutil.log
TODO: Error Handling as Try blocks and -erroraction stop causes runspace to lock up
#>
$Sync.GUITweaks = {
<#
.DESCRIPTION
This Scriptblock is meant to be ran from inside the GUI and will prevent the user from starting another install task.
Input data will look like below and link with the name of the check box. This will then look to the config/applications.json file to find
the modifications for the selected task.
EssTweaksDeBloat,MiscTweaksUTC
.EXAMPLE
Invoke-command $sync.GUIInstallPrograms -ArgumentList "EssTweaksDeBloat,MiscTweaksUTC"
#>
Param($Tweakstorun)
#Check if any check boxes have been checked and if a task is currently running
if ($sync.taskrunning -eq $true){
[System.Windows.MessageBox]::Show($sync.taskmessage,$sync.tasktitle,"OK","Info")
return
}
if($Tweakstorun -notlike "*Tweaks*"){
[System.Windows.MessageBox]::Show("Please check the applications you wish to install",'Nothing to do',"OK","Info")
return
}
$sync.taskrunning = $true
#Invoke a runspace so that the GUI does not lock up
$params = @{
ScriptBlock = $sync.ScriptTweaks
ArgumentList = ("$Tweakstorun")
}
Invoke-Runspace @params
}
$Sync.ScriptTweaks = {
<#
.DESCRIPTION
This scriptblock will run a series of modifications included in the config/tweaks.json file.
TODO: Figure out error handling as any errors in this runspace will crash the powershell session.
.EXAMPLE
$params = @{
ScriptBlock = $sync.ScriptsInstallPrograms
ArgumentList = "EssTweaksTele,EssTweaksServices"
Verbose = $true
}
VerbosePreference = "Continue"
Invoke-Command @params
#>
Param($Tweakstorun)
$Tweakstorun = $Tweakstorun -split ","
$ErrorActionPreference = "SilentlyContinue"
function Write-Logs {
param($Level, $Message, $LogPath)
Invoke-command $sync.WriteLogs -ArgumentList ($Level,$Message, $LogPath)
}
Write-Logs -Level INFO -Message "Gathering required modifications" -LogPath $sync.logfile
$RegistryToModify = $Tweakstorun | ForEach-Object {
$sync.tweaks.$psitem.registry
}
$ServicesToModify = $Tweakstorun | ForEach-Object {
$sync.tweaks.$psitem.service
}
$ScheduledTaskToModify = $Tweakstorun | ForEach-Object {
$sync.tweaks.$psitem.ScheduledTask
}
$AppxToModify = $Tweakstorun | ForEach-Object {
$sync.tweaks.$psitem.appx
}
$ScriptsToRun = $Tweakstorun | ForEach-Object {
$sync.tweaks.$psitem.InvokeScript
}
if($RegistryToModify){
Write-Logs -Level INFO -Message "Starting Registry Modification" -LogPath $sync.logfile
$RegistryToModify | ForEach-Object {
if(!(Test-Path $psitem.path)){
$Step = "create"
Write-Logs -Level INFO -Message "$($psitem.path) did not exist. Creating" -LogPath $sync.logfile
New-Item -Path $psitem.path -Force | Out-Null
}
$step = "set"
Write-Logs -Level INFO -Message "Setting $("$($psitem.path)\$($psitem.name)") to $($psitem.value)" -LogPath $sync.logfile
Set-ItemProperty -Path $psitem.path -Name $psitem.name -Type $psitem.type -Value $psitem.value
}
Write-Logs -Level INFO -Message "Finished setting registry" -LogPath $sync.logfile
}
if($ServicesToModify){
Write-Logs -Level INFO -Message "Starting Services Modification" -LogPath $sync.logfile
$ServicesToModify | ForEach-Object {
Stop-Service "$($psitem.name)"
Set-Service "$($psitem.name)" -StartupType $($psitem.StartupType)
Write-Logs -Level INFO -Message "Service $($psitem.name) set to $($psitem.StartupType)" -LogPath $sync.logfile
}
Write-Logs -Level INFO -Message "Finished setting Services" -LogPath $sync.logfile
}
if($ScheduledTaskToModify){
Write-Logs -Level INFO -Message "Starting ScheduledTask Modification" -LogPath $sync.logfile
$ScheduledTaskToModify | ForEach-Object {
Try{
if($($psitem.State) -eq "Disabled"){
Disable-ScheduledTask -TaskName "$($psitem.name)" -ErrorAction Stop | Out-Null
}
if($($psitem.State) -eq "Enabled"){
Enable-TaskName "$($psitem.name)" -ErrorAction Stop | Out-Null
}
Write-Logs -Level INFO -Message "Scheduled Task $($psitem.name) set to $($psitem.State)" -LogPath $sync.logfile
}Catch{Write-Logs -Level ERROR -Message "Unable to set Scheduled Task $($psitem.name) set to $($psitem.State)" -LogPath $sync.logfile}
}
Write-Logs -Level INFO -Message "Finished setting ScheduledTasks" -LogPath $sync.logfile
}
if($AppxToModify){
Write-Logs -Level INFO -Message "Starting Appx Modification" -LogPath $sync.logfile
$AppxToModify | ForEach-Object {
Try{
Get-AppxPackage -Name $psitem| Remove-AppxPackage -ErrorAction Stop
Get-AppxProvisionedPackage -Online | Where-Object DisplayName -like $psitem | Remove-AppxProvisionedPackage -ErrorAction stop -Online
Write-Logs -Level INFO -Message "Uninstalled $psitem" -LogPath $sync.logfile
}Catch{Write-Logs -Level ERROR -Message "Failed to uninstall $psitem" -LogPath $sync.logfile }
}
Write-Logs -Level INFO -Message "Finished uninstalling Appx" -LogPath $sync.logfile
}
if($ScriptsToRun){
Write-Logs -Level INFO -Message "Running Scripts" -LogPath $sync.logfile
$ScriptsToRun | ForEach-Object {
$Scriptblock = [scriptblock]::Create($psitem)
#Invoke-Command -ScriptBlock $Scriptblock
Start-Process $PSHOME\powershell.exe -Verb runas -ArgumentList "-Command $scriptblock" -Wait
}
#
# Fix bad tweaks made from previous versions
#
Remove-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name "HungAppTimeout" -ErrorAction SilentlyContinue
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management" -Name "ClearPageFileAtShutdown" -Type DWord -Value 0
Write-Logs -Level INFO -Message "Finished Scripts" -LogPath $sync.logfile
}
Write-Logs -Level INFO -Message "Tweaks finished" -LogPath $sync.logfile
if($sync["Form"]){
$sync.taskrunning = $false
[System.Windows.MessageBox]::Show("All modifications have finished",'Tweaks are done!',"OK","Info")
}
}
$Sync.GUIUndoTweaks = {
<#
.DESCRIPTION
This Scriptblock is meant to be ran from inside the GUI and will prevent the user from starting another tweak task.
.EXAMPLE
Invoke-command $sync.GUIUndoTweaks
#>
#Check if any check boxes have been checked and if a task is currently running
if ($sync.taskrunning -eq $true){
[System.Windows.MessageBox]::Show($sync.taskmessage,$sync.tasktitle,"OK","Info")
return
}
$sync.taskrunning = $true
#Invoke a runspace so that the GUI does not lock up
Invoke-Runspace $sync.ScriptUndoTweaks
}
$sync.ScriptUndoTweaks = {
<#
.DESCRIPTION
This scriptblock will undo all modifications from this script.
TODO: Figure out error handling as any errors in this runspace will crash the powershell session.
.EXAMPLE
VerbosePreference = "Continue"
Invoke-Command -ScriptBlock $sync.ScriptUndoTweaks
#>
$ErrorActionPreference = "SilentlyContinue"
function Write-Logs {
param($Level, $Message, $LogPath)
Invoke-command $sync.WriteLogs -ArgumentList ($Level,$Message, $LogPath)
}
Write-Logs -Level INFO -Message "Creating Restore Point incase something bad happens" -LogPath $sync.logfile
Enable-ComputerRestore -Drive "C:\"
Checkpoint-Computer -Description "RestorePoint1" -RestorePointType "MODIFY_SETTINGS"
foreach ($tweak in $($sync.tweaks.psobject.properties)) {
#registry reset
Foreach ($registries in $($tweak.value.registry)){
foreach($registry in $registries){
Write-Logs -Level INFO -Message "Setting $("$($registry.path)\$($registry.name)") to $($registry.OriginalValue)" -LogPath $sync.logfile
Set-ItemProperty -Path $registry.path -Name $registry.name -Type $registry.type -Value $registry.OriginalValue
}
}
Write-Logs -Level INFO -Message "Finished reseting $($tweak.name) registries" -LogPath $sync.logfile
#Services modification
Foreach ($services in $($tweak.value.service)){
foreach($service in $services) {
Stop-Service "$($service.name)"
Set-Service "$($service.name)" -StartupType $($service.OriginalType)
Write-Logs -Level INFO -Message "Service $($service.name) set to $($service.OriginalType)" -LogPath $sync.logfile
}
}
Write-Logs -Level INFO -Message "Finished reseting $($tweak.name) Services" -LogPath $sync.logfile
#Scheduled Tasks Modification
Foreach ($ScheduledTasks in $($tweak.value.ScheduledTask)){
foreach($ScheduledTask in $ScheduledTasks) {
if($($ScheduledTask.OriginalState) -eq "Disabled"){
Disable-ScheduledTask -TaskName "$($ScheduledTask.name)" | Out-Null
}
if($($ScheduledTask.OriginalState) -eq "Enabled"){
Enable-TaskName "$($ScheduledTask.name)" | Out-Null
}
Write-Logs -Level INFO -Message "Scheduled Task $($ScheduledTask.name) set to $($ScheduledTask.OriginalState)" -LogPath $sync.logfile
}
}
Write-Logs -Level INFO -Message "Finished reseting $($tweak.name) Scheduled Tasks" -LogPath $sync.logfile
}
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Session Manager\Power" -Name "HibernteEnabled" -Type Dword -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FlyoutMenuSettings" -Name "ShowHibernateOption" -Type Dword -Value 1
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\Personalization" -Name "NoLockScreen" -ErrorAction SilentlyContinue
If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager")) {
Remove-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\OperationStatusManager" -Recurse -ErrorAction SilentlyContinue
}
If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Siuf\Rules")) {
Remove-Item -Path "HKCU:\SOFTWARE\Microsoft\Siuf\Rules" -Recurse -ErrorAction SilentlyContinue
}
If (!(Test-Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\CloudContent")) {
Remove-Item -Path "HKCU:\SOFTWARE\Policies\Microsoft\Windows\CloudContent" -Recurse -ErrorAction SilentlyContinue
}
If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\AdvertisingInfo")) {
Remove-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\AdvertisingInfo" -Recurse -ErrorAction SilentlyContinue
}
If (!(Test-Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CloudContent")) {
Remove-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CloudContent" -Recurse -ErrorAction SilentlyContinue
}
If (!(Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location")) {
Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location" -Recurse -ErrorAction SilentlyContinue
}
Write-Logs -Level INFO -Message "Unrestricting AutoLogger directory" -LogPath $sync.logfile
$autoLoggerDir = "$env:PROGRAMDATA\Microsoft\Diagnosis\ETLLogs\AutoLogger"
icacls $autoLoggerDir /grant:r SYSTEM:`(OI`)`(CI`)F | Out-Null
Write-Logs -Level INFO -Message "Reset Local Group Policies to Stock Defaults" -LogPath $sync.logfile
# cmd /c secedit /configure /cfg %windir%\inf\defltbase.inf /db defltbase.sdb /verbose
cmd /c RD /S /Q "%WinDir%\System32\GroupPolicyUsers"
cmd /c RD /S /Q "%WinDir%\System32\GroupPolicy"
cmd /c gpupdate /force
Write-Logs -Level INFO -Message "Restoring Clipboard History..." -LogPath $sync.logfile
Remove-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Clipboard" -Name "EnableClipboardHistory" -ErrorAction SilentlyContinue
Remove-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\System" -Name "AllowClipboardHistory" -ErrorAction SilentlyContinue
Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name "UserPreferencesMask" -Type Binary -Value ([byte[]](158,30,7,128,18,0,0,0))
if($sync["Form"]){
$sync.taskrunning = $false
[System.Windows.MessageBox]::Show("All tweaks have been removed",'Undo is done!',"OK","Info")
}
}
#===========================================================================
# Tab 3 - Config Buttons
#===========================================================================
<#
This section is working as expected and logs output to console and $ENV:Temp\winutil.log
TODO: Error Handling as Try blocks and -erroraction stop causes runspace to lock up
#>
$Sync.GUIFeatures = {
<#
.DESCRIPTION
This Scriptblock is meant to be ran from inside the GUI and will prevent the user from starting another install task.
Input data will look like below and link with the name of the check box. This will then look to the config/features.json file to find
the install commands for the selected features.
Featureshyperv,Featureslegacymedia
.EXAMPLE
Invoke-command $sync.GUIInstallPrograms -ArgumentList "Featureshyperv,Featureslegacymedia"
#>
param ($featuretoinstall)
#Check if any check boxes have been checked and if a task is currently running
if ($sync.taskrunning -eq $true){
[System.Windows.MessageBox]::Show($sync.taskmessage,$sync.tasktitle,"OK","Info")
return
}
if($featuretoinstall -notlike "*Features*"){
[System.Windows.MessageBox]::Show("Please check the features you wish to install",'Nothing to do',"OK","Info")
return
}
$sync.taskrunning = $true
#Invoke a runspace so that the GUI does not lock up
$params = @{
ScriptBlock = $sync.ScriptFeatureInstall
ArgumentList = ("$featuretoinstall")
}
Invoke-Runspace @params
}
$sync.ScriptFeatureInstall = {
<#
.DESCRIPTION
This scriptblock will install the selected features from the config/features.json file.
TODO: Figure out error handling as any errors in this runspace will crash the powershell session.
.EXAMPLE
$params = @{
ScriptBlock = $sync.ScriptFeatureInstall
ArgumentList = "Featureshyperv,Featureslegacymedia"
Verbose = $true
}
VerbosePreference = "Continue"
Invoke-Command @params
#>
param ($featuretoinstall)
$featuretoinstall = $featuretoinstall -split ","
function Write-Logs {
param($Level, $Message, $LogPath)
Invoke-command $sync.WriteLogs -ArgumentList ($Level,$Message, $LogPath)
}
Foreach ($feature in $featuretoinstall){
$sync.feature.$feature | ForEach-Object {
Try{
Write-Logs -Level INFO -Message "Installing Windows Feature $psitem" -LogPath $sync.logfile
Enable-WindowsOptionalFeature -Online -FeatureName "$psitem" -All -NoRestart
Write-output $psitem
}Catch{Write-Logs -Level ERROR -Message "Failed to install $psitem" -LogPath $sync.logfile}
}
}
Write-Logs -Level INFO -Message "Finished Installing features" -LogPath $sync.logfile
if($sync["Form"]){
$sync.taskrunning = $false
[System.Windows.MessageBox]::Show("Features have been installed",'Installs are done!',"OK","Info")
}
}
#===========================================================================
# Tab 4 - Updates Buttons
#===========================================================================
$Sync.GUIUpdates = {
<#
.DESCRIPTION
Current Options
"Updatesdefault"
"Updatesdisable"
"Updatessecurity"
.EXAMPLE
Invoke-command $sync.GUIUpdates -ArgumentList "Updatesdefault"
#>
param ($updatestoconfigure)
#Check if any check boxes have been checked and if a task is currently running
if ($sync.taskrunning -eq $true){
[System.Windows.MessageBox]::Show($sync.taskmessage,$sync.tasktitle,"OK","Info")
return
}
$sync.taskrunning = $true
#Invoke a runspace so that the GUI does not lock up
$params = @{
ScriptBlock = $sync.ScriptUpdates
ArgumentList = ("$updatestoconfigure")
}
Invoke-Runspace @params
}
$sync.ScriptUpdates = {
<#
.DESCRIPTION
This scriptblock will install the selected features from the config/features.json file.
TODO: Figure out error handling as any errors in this runspace will crash the powershell session.
.EXAMPLE
$params = @{
ScriptBlock = $sync.ScriptFeatureInstall
ArgumentList = "Featureshyperv,Featureslegacymedia"
Verbose = $true
}
VerbosePreference = "Continue"
Invoke-Command @params
#>
param ($updatestoconfigure)
function Write-Logs {
param($Level, $Message, $LogPath)
Invoke-command $sync.WriteLogs -ArgumentList ($Level,$Message, $LogPath)
}
if($updatestoconfigure -eq "FixesUpdate"){
# Source: https://github.com/rgl/windows-vagrant/blob/master/disable-windows-updates.ps1 reversed!
Set-StrictMode -Version Latest
$ProgressPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Stop'
trap {
Write-Logs -Level "ERROR" -LogPath $sync.logfile -Message $psitem
Write-Logs -Level "INFO" -LogPath $sync.logfile -Message "Sleeping for 60m to give you time to look around the virtual machine before self-destruction..."