forked from MyDrift-user/WinToolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wintoolbox.ps1
1132 lines (965 loc) · 47 KB
/
wintoolbox.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 ###
### ###
################################################################################################################
# Define the version of the script based on the current date
$scriptVersion = (Get-Date).ToString("yyyyMMdd")
<#
.NOTES
Author : MyDrift @mydrift-user
GitHub : https://github.com/mydrift-user
? : pnp powershell instead of Get-Credential?
TODO : create session without prequisits on remote machine
TODO : delete logs older than 30 days | create config for that (checkbox in settings tab (rename sources to settings) rename sources as subtab)
TODO : package as .exe (github & website)
TODO : save an additional script and put it in task scheduler. after 30 days of not running the script it deleats the logs, the task and itself.
TODO : Run on system boot -> task scheduler checks for windows version change and then runs the selected/needed tweaks.
#>
# check if codes are running in an elevated session. if not, restart the script in an elevated session
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
# If not elevated, relaunch the script in a new elevated PowerShell session
#TODO save script in directory, change escapedcommand to run that saved script instead of rerequest code.
$escapedCommand = 'irm mdiana.win | iex'
Start-Process PowerShell -ArgumentList "-Command", $escapedCommand -Verb RunAs
exit
}
Write-Host "
MMMMMMMM MMMMMMMM DDDDDDDDDDDDDD
M:::::::M M:::::::M D:::::::::::::DDD
M::::::::M M::::::::M D::::::::::::::::DD
M:::::::::M M:::::::::M DDD:::::DDDDD::::::D
M::::::::::M M::::::::::M D:::::D D::::::D
M:::::::::::M M:::::::::::M D:::::D D::::::D
M:::::::M::::M M::::M:::::::M D:::::D D::::::D
M::::::M M::::M M::::M M::::::M D:::::D D::::::D
M::::::M M::::M::::M M::::::M D:::::D D::::::D
M::::::M M:::::::M M::::::M D:::::D D::::::D
M::::::M M:::::M M::::::M D:::::D D::::::D
M::::::M MMMMM M::::::M D:::::D D::::::D
M::::::M M::::::M DDD:::::DDDDD::::::D
M::::::M M::::::M D::::::::::::::::DD
M::::::M M::::::M D:::::::::::::DDD
MMMMMMMM MMMMMMMM DDDDDDDDDDDDDD
========Mattia Diana========
=====Powershell Toolbox=====
=======Managing Device======
Version: $scriptVersion
"
$directory = "C:\Windows\WinToolBox"
# Check if the logs subdirectory exists within the main directory and create it if it doesn't
if (-not (Test-Path -Path "$directory\Logs")) {
New-Item -Path "$directory\Logs" -ItemType Directory -Force | Out-Null
}
$dateTime = Get-Date -Format "dd-MM-yyyy_HH-mm-ss"
Start-Transcript -Path "$directory\Logs\WinToolBox_$dateTime.log" -Append
function Get-JsonConfig {
param (
[string]$ConfigPath = "$directory\config.json"
)
if (Test-Path -Path $ConfigPath) {
$json = Get-Content -Path $ConfigPath -Raw | ConvertFrom-Json
return $json
} else {
return $null
}
}
function Set-JsonConfig {
param (
[Parameter(Mandatory)]
[PSCustomObject]$JsonData,
[string]$ConfigPath = "$directory\config.json"
)
$JsonData | ConvertTo-Json -Depth 5 | Set-Content -Path $ConfigPath
}
# Load WPF and XAML libraries
Add-Type -AssemblyName PresentationCore, WindowsBase, PresentationFramework, System.Drawing, WindowsFormsIntegration
# WPF GUI Design in XAML
[xml]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WinToolbox" Height="450" Width="800">
<Window.Resources>
<Style x:Key="ToggleSwitchStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid x:Name="toggleSwitch">
<Border x:Name="Border" CornerRadius="11"
Background="#FFFFFFFF"
Width="50" Height="25"> <!-- Adjusted width here -->
<Border.Effect>
<DropShadowEffect ShadowDepth="0.5" Direction="0" Opacity="0.3" />
</Border.Effect>
<Ellipse x:Name="Ellipse" Fill="#FFFFFFFF" Stretch="Uniform"
Margin="2 2 2 1"
Stroke="Gray" StrokeThickness="0.2"
HorizontalAlignment="Left" Width="22">
<Ellipse.Effect>
<DropShadowEffect BlurRadius="10" ShadowDepth="1" Opacity="0.3" Direction="260" />
</Ellipse.Effect>
</Ellipse>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="ToggleButton.IsChecked" Value="False">
<Setter TargetName="Border" Property="Background" Value="#C2283B" />
<Setter TargetName="Ellipse" Property="Margin" Value="2 2 2 1" />
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="Border"
Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="#34A543" Duration="0:0:0.1" />
<ThicknessAnimation Storyboard.TargetName="Ellipse"
Storyboard.TargetProperty="Margin"
To="26 2 2 1" Duration="0:0:0.1" /> <!-- Adjusted margin for smaller width -->
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="Border"
Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
To="#C2283B" Duration="0:0:0.1" />
<ThicknessAnimation Storyboard.TargetName="Ellipse"
Storyboard.TargetProperty="Margin"
To="2 2 2 1" Duration="0:0:0.1" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
<Setter Property="Foreground" Value="{DynamicResource IdealForegroundColorBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>
</Window.Resources>
<DockPanel LastChildFill="True">
<Expander Name="DeviceMGMTexpander" ExpandDirection="Right" IsExpanded="False">
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" /> <!-- For static controls: TextBox and Buttons -->
<RowDefinition Height="*" /> <!-- For ScrollViewer, will take up remaining space -->
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Margin="10">
<TextBox Name="txtHostname" />
<Button Name="btnAdd" Content="Add" />
<Button Name="btnRemove" Content="Remove Selection" />
</StackPanel>
<!-- ScrollViewer in a separate row, taking up the remaining space -->
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Hidden">
<StackPanel Name="panelDevices" />
</ScrollViewer>
</Grid>
</Expander>
<TextBox x:Name="txtsearch" HorizontalAlignment="Left" Height="23" Margin="0,0,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
<TabControl Grid.Column="1" Margin="10">
<TabItem Header="Windows">
<!-- Nested TabControl for the three new tabs -->
<TabControl x:Name="subTabControl">
<TabItem Header="Applications" x:Name="tabApplications">
<Grid> <!-- Ein Grid als Container für die gesamte Struktur -->
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/> <!-- Reihe für die Buttons -->
<RowDefinition Height="*"/> <!-- Reihe für den ScrollViewer -->
</Grid.RowDefinitions>
<!-- Buttons oben im Grid -->
<StackPanel Grid.Row="0" Orientation="Horizontal" HorizontalAlignment="Left" Margin="10">
<Button Name="btnInstallSelection" Content="Install/Upgrade Selection" Margin="5"/>
<Button Name="btnUpdateAll" Content="Update All" Margin="5"/>
<Button Name="btnUninstallSelection" Content="Uninstall Selection" Margin="5"/>
<Button Name="btnShowInstalled" Content="Show Installed" Margin="5"/>
<Button Name="btnClearSelection" Content="Clear Selection" Margin="5"/>
</StackPanel>
<!-- ScrollViewer für die Applikationsliste in der zweiten Reihe des Grids -->
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">
<WrapPanel Name="appspanel" SnapsToDevicePixels="True" Orientation="Horizontal">
<!-- Dynamically added CheckBoxes will be placed here -->
</WrapPanel>
</ScrollViewer>
</Grid>
</TabItem>
<TabItem Header="Tweaks">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- First Column for checkboxes and buttons -->
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Checkboxes StackPanel -->
<StackPanel Name="tweaksPanel" Margin="10">
<!-- Checkboxes will be added here in the script -->
</StackPanel>
<!-- Buttons at the bottom -->
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center" Margin="10">
<Button Name="btnRunTweaks" Content="Run Selected" Margin="5" Width="100" />
<Button Name="btnUndoTweaks" Content="Undo Selected" Margin="5" Width="100" />
</StackPanel>
</Grid>
<!-- Second Column for toggle switch and other controls -->
<StackPanel Grid.Column="1" Margin="10">
<ToggleButton Name="btnToggleDarkMode" Style="{StaticResource ToggleSwitchStyle}" Margin="10" IsChecked="False" HorizontalAlignment="Left"/>
<TextBlock Name="txtToggleTheme" VerticalAlignment="Center" Text="Dark Mode" HorizontalAlignment="Left"/>
<ToggleButton Name="btnToggleBingSearch" Style="{StaticResource ToggleSwitchStyle}" Margin="10" IsChecked="False" HorizontalAlignment="Left"/>
<TextBlock Name="txtToggleBingSearchStatus" VerticalAlignment="Center" Text="Bing Search in Start Menu" HorizontalAlignment="Left"/>
<Button Name="btnCreateShortcut" Content="Create Shortcut" Margin="5" HorizontalAlignment="Left"/>
</StackPanel>
</Grid>
</TabItem>
</TabControl>
</TabItem>
<TabItem Header="Sources">
<StackPanel Margin="10">
<DockPanel LastChildFill="False">
<TextBox Name="txtNewSource" DockPanel.Dock="Left" Width="200" Margin="0,0,5,10"/>
<ComboBox Name="cmbSourceType" Width="120" Margin="0,0,5,10">
<ComboBoxItem Content="Application"/>
<ComboBoxItem Content="Tweak"/>
</ComboBox>
<Button Name="btnAddSource" Content="Add" Width="75" Margin="5,0,0,10"/>
</DockPanel>
<TextBlock Margin="0,20,0,0" FontWeight="Bold">Current Sources:</TextBlock>
<ScrollViewer VerticalScrollBarVisibility="Visible">
<StackPanel Name="panelSources" />
</ScrollViewer>
<Button Name="btnDeleteSource" Content="Delete Source" Margin="10"/>
</StackPanel>
</TabItem>
</TabControl>
</DockPanel>
</Window>
"@
# Parse the XAML
$reader = New-Object System.Xml.XmlNodeReader $xaml
$window = [Windows.Markup.XamlReader]::Load($reader)
$subTabControl = $window.FindName("subTabControl")
# Check for Internet connection before showing the window
$tabApplications = $window.FindName("tabApplications") # Get the Applications tab reference
$network = $null
if (-not (Test-Connection 8.8.8.8 -Quiet -Count 1)) {
$tabApplications.Visibility = [System.Windows.Visibility]::Collapsed
$subTabControl.SelectedIndex = 1
Write-Host "No Internet Connection: Hiding Applications Tab"
$network = "false"
} else {
$tabApplications.Visibility = [System.Windows.Visibility]::Visible
$subTabControl.SelectedIndex = 0
#Write-Host "Internet Connection Detected: Displaying Applications Tab"
$network = "true"
}
# URL to the ICO file
$iconUrl = "https://raw.githubusercontent.com/MyDrift-user/WinToolbox/main/logo.ico"
$iconPath = "$directory\assets\logo.ico"
# Ensure the directory exists
$directoryPath = [System.IO.Path]::GetDirectoryName($iconPath)
if (-not (Test-Path -Path $directoryPath)) {
Write-Host "Creating directory: $directoryPath"
New-Item -Path $directoryPath -ItemType Directory -Force
}
# Download the ICO file
if ($network -eq "true") {
try {
Invoke-WebRequest -Uri $iconUrl -OutFile $iconPath
# Create an ImageSource from the ICO file
$iconUri = New-Object System.Uri($iconPath)
$iconBitmap = New-Object System.Windows.Media.Imaging.BitmapImage($iconUri)
# Set the Window Icon
$window.Icon = $iconBitmap
} catch {
Write-Host "Failed to download & load the ICO file. Error: $($_.Exception.Message)"
}
}
# Access controls from the parsed XAML
$txtHostname = $window.FindName("txtHostname")
$btnAdd = $window.FindName("btnAdd")
$btnRemove = $window.FindName("btnRemove")
$panelDevices = $window.FindName("panelDevices")
$btnRun = $window.FindName("btnRun")
$txtNewSource = $window.FindName("txtNewSource")
$cmbSourceType = $window.FindName("cmbSourceType")
$btnAddSource = $window.FindName("btnAddSource")
$lstSources = $window.FindName("lstSources")
$panelSources = $window.FindName("panelSources")
$btnDeleteSource = $window.FindName("btnDeleteSource")
$btnAddSource.Add_Click({ Add-Source })
$btnDeleteSource.Add_Click({ Remove-Source })
$btnAdd.Add_Click({ Add-Device })
$btnRemove.Add_Click({ Remove-Device })
$btnInstallSelection = $window.FindName("btnInstallSelection")
$btnInstallSelection.Add_Click({ Install-SelectedApps })
$btnUninstallSelection = $window.FindName("btnUninstallSelection")
$btnUpdateAll = $window.FindName("btnUpdateAll")
$btnUpdateAll.Add_Click({ Update-AllApps })
$btnShowInstalled = $window.FindName("btnShowInstalled")
$btnUninstallSelection.Add_Click({ Uninstall-Selection })
$btnShowInstalled.Add_Click({ Show-Installed })
# Shortcut Creation
$btnCreateShortcut = $window.FindName("btnCreateShortcut")
$btnCreateShortcut.Add_Click({ Create-Shortcut })
# Correct XML manipulation
$appspanel = $window.FindName("appspanel")
$config = Get-JsonConfig
$DeviceMGMTexpander = $window.FindName("DeviceMGMTexpander")
if ($config -and $config.DeviceMGMTexpander -and $config.DeviceMGMTexpander.expanded -eq "True") {
$DeviceMGMTexpander.IsExpanded = $true
} else {
$DeviceMGMTexpander.IsExpanded = $false
}
# Handler for clearing all application checkboxes
$btnClearSelection = $window.FindName("btnClearSelection")
$btnClearSelection.Add_Click({ Clear-Selection })
function Clear-Selection {
# Iterate through all checkboxes in the applications panel
foreach ($expander in $appspanel.Children) {
$stackPanel = $expander.Content
foreach ($checkBox in $stackPanel.Children) {
$checkBox.IsChecked = $false
}
}
}
function Install-PackageManagers {
if ($network -eq "true") {
# Check if Chocolatey is installed
if (Get-Command choco -ErrorAction SilentlyContinue) {
$currentVersion = choco --version | Out-String
#Write-Host "Current Chocolatey version: $currentVersion"
try {
#Write-Host "Checking for updates for Chocolatey..."
$output = choco upgrade chocolatey -y | Out-String # Capture the full output as a string
if ($output -like "*is the latest version available based on your source(s)*") {
Write-Host ""
Write-Host "Chocolatey is installed. Version: $currentVersion"
} elseif ($output -like "*Chocolatey upgraded 0/1 packages*") {
Write-Host "No updates were needed; Chocolatey is already at the latest version. Version: $currentVersion"
} elseif ($output -like "*Chocolatey upgraded 1/1 packages*" -or $output -like "*upgraded*") {
$newVersion = choco --version | Out-String
Write-Host "Chocolatey has been updated to the latest version: $newVersion"
} else {
Write-Host "Chocolatey update status is unclear. Check the output above for more details."
}
} catch {
Write-Host "An error occurred while trying to update Chocolatey: $($_.Exception.Message)"
}
} else {
Write-Host "Chocolatey is not installed. Installing now."
try {
# Installing Chocolatey
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
$installedVersion = choco --version | Out-String
Write-Host "Chocolatey installed successfully. Version: $installedVersion"
} catch {
Write-Host "Failed to install Chocolatey: $($_.Exception.Message)"
}
}
# Check and install/update winget
try {
$wingetInstalled = winget --version
if ($wingetInstalled) {
Write-Host "winget is installed. Version: $wingetInstalled"
} else {
throw "winget not installed"
}
} catch {
Write-Host "Attempting to install/update winget..."
try {
if (Get-Command choco -ErrorAction SilentlyContinue) {
try {
choco install winget -y
Write-Host "===========================================" -ForegroundColor Green
Write-Host "--- Installed Winget Successfully ---" -ForegroundColor Green
Write-Host "===========================================" -ForegroundColor Green
} catch {
Write-Host "Failed to install/update winget from Chocolatey. Error: $($_.Exception.Message)"
}
}
} catch {
Write-Host "
Chocolatey is not installed. Attempting to install winget from GitHub...
This Method is in testing phase. Please report any issues to Github.
"
Invoke-WebRequest -Uri "https://github.com/microsoft/winget-cli/releases/latest/download/Microsoft.DesktopAppInstaller.msixbundle" -OutFile "$env:TEMP\Microsoft.DesktopAppInstaller.msixbundle"
Add-AppxPackage -Path "$env:TEMP\Microsoft.DesktopAppInstaller.msixbundle" -ForceApplicationShutdown
Write-Host "winget installed/updated successfully from GitHub."
Remove-Item -Path "$env:TEMP\Microsoft.DesktopAppInstaller.msixbundle" -Force
}
}
} elseif ($network -eq "false") {
#Write-Host "Network is not available. Skipping package manager checks."
}
}
Install-PackageManagers
function Is-AppInstalledWinget($app) {
if (-not (Get-Command "winget" -ErrorAction SilentlyContinue)) {
Write-Host "Winget is not installed."
return $false
}
try {
$installedApps = winget list --id $app -e
if ($installedApps -match $app) {
Write-Host "$app is installed via Winget."
return $true
} else {
Write-Host "$app is not installed via Winget."
return $false
}
} catch {
Write-Host "Failed to check application with Winget: $($_.Exception.Message)"
return $false
}
}
function Is-AppInstalledChoco($app) {
if (-not (Get-Command "choco" -ErrorAction SilentlyContinue)) {
Write-Host "Chocolatey is not installed."
return $false
}
try {
$installedApps = choco list --localonly | Select-String -Pattern "$app"
if ($installedApps -match $app) {
Write-Host "$app is installed via Chocolatey."
return $true
} else {
Write-Host "$app is not installed via Chocolatey."
return $false
}
} catch {
Write-Host "Failed to check application with Chocolatey: $($_.Exception.Message)"
return $false
}
}
function Modify-SelectedApps($action) {
$commands = @() # Initialize an array to hold all commands
foreach ($expander in $appspanel.Children) {
$stackPanel = $expander.Content
foreach ($checkBox in $stackPanel.Children) {
if ($checkBox.IsChecked) {
$appInfo = $checkBox.Tag
switch ($action) {
"modify" {
if ($appInfo.winget -and $appInfo.winget -ne "na") {
$commands += "try { winget install $($appInfo.winget) -e --accept-source-agreements --accept-package-agreements; } catch { Write-Host 'Failed to install $($appInfo.winget): `$($_.Exception.Message)' }"
$commands += "try { winget upgrade $($appInfo.winget) -e --accept-source-agreements --accept-package-agreements; } catch { Write-Host 'Failed to modify $($appInfo.winget): `$($_.Exception.Message)' }"
}
elseif ($appInfo.choco -and $appInfo.choco -ne "na") {
$commands += "try { choco install $($appInfo.choco) -y; } catch { Write-Host 'Failed to install $($appInfo.choco): `$($_.Exception.Message)' }"
$commands += "try { choco upgrade $($appInfo.choco) -y; } catch { Write-Host 'Failed to upgrade $($appInfo.choco): `$($_.Exception.Message)' }"
}
}
"uninstall" {
$commands += "
try {
winget uninstall --id $($appInfo.winget);
} catch {
Write-Host 'Failed to uninstall $($appInfo.winget): `$($_.Exception.Message)'
try {
choco uninstall $($appInfo.choco) -y;
} catch {
Write-Host 'Failed to uninstall $($appInfo.choco): `$($_.Exception.Message)'
}
}"
}
}
}
}
}
if ($action -eq "updateall") {
$commands += "try { winget upgrade --all --accept-source-agreements --accept-package-agreements; } catch { Write-Host 'Failed to upgrade all Winget packages: `$($_.Exception.Message)' }"
$commands += "try { choco upgrade all -y; } catch { Write-Host 'Failed to upgrade all Chocolatey packages: `$($_.Exception.Message)' }"
}
if ($commands.Count -gt 0) {
$scriptBlock = $commands -join "; "
Write-Host "Executing the following commands in a new PowerShell window and will close automatically when done:"
Write-Host $scriptBlock
Start-Process "powershell" -ArgumentList "-NoProfile", "-Command", $scriptBlock -WindowStyle Normal
} else {
Write-Host "No applications selected or no valid action found."
}
}
function Install-SelectedApps {
Modify-SelectedApps "modify"
}
function Uninstall-Selection {
Modify-SelectedApps "uninstall"
}
function Update-AllApps {
Modify-SelectedApps "updateall"
}
function Escape-Regex ($string) {
[regex]::Escape($string)
}
# Ensure the rest of your script follows here...
function Show-Installed {
# Example usage within this function
$chocoInstalled = if (Get-Command "choco" -ErrorAction SilentlyContinue) {
choco list --localonly
} else {
""
}
$wingetInstalled = if (Get-Command "winget" -ErrorAction SilentlyContinue) {
winget list
} else {
""
}
Clear-Selection
# Iterate through checkboxes...
foreach ($expander in $appspanel.Children) {
$stackPanel = $expander.Content
foreach ($checkBox in $stackPanel.Children) {
$appInfo = $checkBox.Tag
$isInstalled = $false
if ($appInfo.choco -and $appInfo.choco -ne "na") {
$escapedChoco = Escape-Regex $appInfo.choco
$isInstalled = $isInstalled -or ($chocoInstalled -match $escapedChoco)
}
if ($appInfo.winget -and $appInfo.winget -ne "na") {
$escapedWinget = Escape-Regex $appInfo.winget
$isInstalled = $isInstalled -or ($wingetInstalled -match $escapedWinget)
}
$checkBox.IsChecked = $isInstalled
}
}
}
function Get-SystemTheme {
$key = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize'
$systemThemeValue = Get-ItemPropertyValue -Path $key -Name "SystemUsesLightTheme"
if ($systemThemeValue -eq 0) {
return "Dark"
} else {
return "Light"
}
}
$btnToggleDarkMode = $window.FindName("btnToggleDarkMode")
$systemTheme = Get-SystemTheme
if ($systemTheme -eq "Dark") {
$btnToggleDarkMode.IsChecked = $true
$btnToggleDarkMode.Content = "Disable Dark Mode"
} else {
$btnToggleDarkMode.IsChecked = $false
$btnToggleDarkMode.Content = "Enable Dark Mode"
}
$btnToggleBingSearch = $window.FindName("btnToggleBingSearch")
$btnToggleBingSearch.Add_Checked({
# Enable Bing Search in Start Menu
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "BingSearchEnabled" -Value 1
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "CortanaConsent" -Value 1
$btnToggleBingSearch.Content = "Disable Bing Search"
})
$btnToggleBingSearch.Add_Unchecked({
# Disable Bing Search in Start Menu
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "BingSearchEnabled" -Value 0
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "CortanaConsent" -Value 0
$btnToggleBingSearch.Content = "Enable Bing Search"
})
$bingSearchEnabled = Get-ItemPropertyValue -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Search" -Name "BingSearchEnabled"
if ($bingSearchEnabled -eq 1) {
$btnToggleBingSearch.IsChecked = $true
$btnToggleBingSearch.Content = "Disable Bing Search"
} else {
$btnToggleBingSearch.IsChecked = $false
$btnToggleBingSearch.Content = "Enable Bing Search"
}
function Add-TweakOptions {
$tweaksPanel = $window.FindName("tweaksPanel")
if ($null -eq $tweaksPanel) {
Write-Host "Tweaks panel not found."
return
}
$tweakOptions = @(
@{
Name="Delete Temporary Files";
Tooltip="Erases TEMP folder";
ScriptBlock={ Remove-Item -Path "C:\Windows\Temp\*" -Force -Recurse };
UndoScriptBlock={ Write-Host "Cannot undo delete." } },
@{
Name="Disk Cleanup";
Tooltip="Runs Disk Cleanup on Drive C: and removes old Windows Updates";
ScriptBlock={ Start-Process "cleanmgr" -ArgumentList "/sagerun:1" };
UndoScriptBlock={ Write-Host "Disk cleanup cannot be undone." } },
@{
Name="Set Services to Manual";
Tooltip="Stops Services from running if they are not needed";
ScriptBlock={ Get-Service | Where-Object {$_.StartType -eq 'Automatic'} | Set-Service -StartupType Manual };
UndoScriptBlock={ Write-Host "Service changes should be manually reviewed to undo." } }
)
foreach ($tweak in $tweakOptions) {
$checkBox = New-Object System.Windows.Controls.CheckBox
$checkBox.Content = $tweak.Name
$checkBox.Margin = New-Object System.Windows.Thickness(5)
$checkBox.Tag = $tweak # Store the entire tweak object in the Tag property
# ToolTip setup
$toolTip = New-Object System.Windows.Controls.ToolTip
$toolTip.Content = $tweak.Tooltip
$checkBox.ToolTip = $toolTip # Ensure this line correctly sets the tooltip object
# Add CheckBox to the StackPanel
$tweaksPanel.Children.Add($checkBox) | Out-Null
}
}
Add-TweakOptions
function Run-SelectedTweaks {
$tweaksPanel = $window.FindName("tweaksPanel")
$tweaksPanel.Children | Where-Object { $_ -is [System.Windows.Controls.CheckBox] -and $_.IsChecked } | ForEach-Object {
$tweak = $_.Tag
Write-Host "Running tweak for: $($tweak.Name)"
& $tweak.ScriptBlock
}
}
function Undo-SelectedTweaks {
$tweaksPanel = $window.FindName("tweaksPanel")
$tweaksPanel.Children | Where-Object { $_ -is [System.Windows.Controls.CheckBox] -and $_.IsChecked } | ForEach-Object {
$tweak = $_.Tag
Write-Host "Undoing tweak for: $($tweak.Name)"
& $tweak.UndoScriptBlock
}
}
# Adding click event handlers to buttons
$btnRunTweaks = $window.FindName("btnRunTweaks")
$btnUndoTweaks = $window.FindName("btnUndoTweaks")
$btnRunTweaks.Add_Click({
Run-SelectedTweaks
})
$btnUndoTweaks.Add_Click({
Undo-SelectedTweaks
})
$btnToggleDarkMode.Add_Checked({
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name "SystemUsesLightTheme" -Value 0
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name "AppsUseLightTheme" -Value 0
$btnToggleDarkMode.Content = "Disable Dark Mode"
})
$btnToggleDarkMode.Add_Unchecked({
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name "SystemUsesLightTheme" -Value 1
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name "AppsUseLightTheme" -Value 1
$btnToggleDarkMode.Content = "Enable Dark Mode"
})
function Invoke-RemoteCommand {
param(
[ScriptBlock]$ScriptBlock
)
$selectedDevices = $panelDevices.Children | Where-Object { $_.IsChecked -eq $true } | ForEach-Object { $_.Content }
foreach ($device in $selectedDevices) {
Invoke-Command -ComputerName $device -ScriptBlock $ScriptBlock
}
}
function Create-Shortcut {
param(
[string]$ScriptUrl = "http://mdiana.win",
[string]$LocalPath = "$directory\Scripts\Local-WinToolBox.ps1"
)
# Ensure the directory exists where the script will be saved
$directory = Split-Path -Path $LocalPath -Parent
if (-not (Test-Path -Path $directory)) {
New-Item -Path $directory -ItemType Directory -Force | Out-Null
Write-Host "Created directory: $directory"
}
try {
# Download the script from the URL
$scriptContent = Invoke-RestMethod -Uri $ScriptUrl
$scriptContent | Out-File -FilePath $LocalPath -Force
Write-Host "Script saved successfully to $LocalPath"
} catch {
Write-Host "Failed to download or save the script. Error: $($_.Exception.Message)"
}
# Define the path where the script will be saved
$scriptPath = "$directory\Scripts\Local-director.ps1"
# Ensure the directory exists
$directory = Split-Path -Path $scriptPath
if (-not (Test-Path $directory)) {
New-Item -Path $directory -ItemType Directory -Force
}
# Script content that checks internet connection and executes commands accordingly
$scriptContent = @'
if (Test-Connection 8.8.8.8 -Quiet -Count 1) {
try {
# If there is Internet, run the script from mdiana.win
irm mdiana.win | iex
} catch {
Write-Host "Failed to load script from mdiana.win: $($_.Exception.Message)"
Pause
}
} else {
try {
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
# If not elevated, relaunch the script in a new elevated PowerShell session
$escapedCommand = 'irm C:\Windows\WinToolBox\Scripts\Local-WinToolBox.ps1 | iex'
Start-Process PowerShell -ArgumentList "-Command", $escapedCommand -Verb RunAs
exit
}
} catch {
Write-Host "Failed to run the local script: $($_.Exception.Message)"
Pause
}
}
'@
# Write the script content to the file without BOM
$utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllLines($scriptPath, $scriptContent, $utf8NoBomEncoding)
Write-Host "Script created or updated at $scriptPath"
# Load Windows Forms and drawing assemblies
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# Create a Save File Dialog
$saveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$saveFileDialog.initialDirectory = [Environment]::GetFolderPath([Environment+SpecialFolder]::DesktopDirectory)
$saveFileDialog.filter = "Shortcut files (*.lnk)|*.lnk"
$saveFileDialog.FileName = "WinToolBox.lnk"
# Show the Save File Dialog
if ($saveFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
$shortcutPath = $saveFileDialog.FileName
# Specify the target PowerShell command
$command = "irm $directory\Scripts\Local-director.ps1 | iex"
# Create a shell object
$shell = New-Object -ComObject WScript.Shell
# Create a shortcut object
$shortcut = $shell.CreateShortcut($shortcutPath)
if (Test-Path -Path "$directory\assets\logo.ico") {
$shortcut.IconLocation = "$directory\assets\logo.ico"
} else {
$shortcut.IconLocation = "powershell.exe"
}
# Set properties of the shortcut
$shortcut.TargetPath = "powershell.exe"
$shortcut.Arguments = "-NoProfile -ExecutionPolicy Bypass -Command `"$command`""
# Save the shortcut
$shortcut.Save()
Write-Host "Shortcut created at: $shortcutPath"
} else {
Write-Host "User cancelled the shortcut creation."
}
}
$configPath = "$directory\WinToolBox.config"
if (Test-Path $configPath) {
$savedSourceEntries = Get-Content $configPath
foreach ($entry in $savedSourceEntries) {
$checkbox = New-Object System.Windows.Controls.CheckBox
$checkbox.Content = $entry
$checkbox.Margin = New-Object System.Windows.Thickness(5)
$panelSources.Children.Add($checkbox)
}
}
if ($network -eq "true") {
$jsonUrls = @(
"https://raw.githubusercontent.com/ChrisTitusTech/winutil/main/config/applications.json",
"https://raw.githubusercontent.com/MyDrift-user/WinToolbox/main/apps.json"
)
# Initialize a hashtable to store applications by category
$appsByCategory = @{}
# Iterate over the URLs and fetch JSON content from each
foreach ($jsonUrl in $jsonUrls) {
$jsonContent = Invoke-WebRequest -Uri $jsonUrl -UseBasicParsing | ConvertFrom-Json
# Organize applications by category
foreach ($app in $jsonContent.PSObject.Properties) {
$category = $app.Value.category
$choco = $app.Value.choco
$winget = $app.Value.winget
$link = $app.Value.link
$description = $app.Value.description
$content = $app.Value.content
#write-Host $content $description $link $choco $winget
#write-host ""
if (-not $category) {
$category = "Uncategorized" # Assign a default category if null or empty
}
if (-not $appsByCategory.ContainsKey($category)) {
$appsByCategory[$category] = @()
}
$appsByCategory[$category] += $app
}
}
# Clear existing items in appspanel to avoid duplicates
$appspanel.Children.Clear()
# Sort categories alphabetically before creating expanders
$sortedCategories = $appsByCategory.Keys | Sort-Object
foreach ($category in $sortedCategories) {
$expander = New-Object System.Windows.Controls.Expander
$expander.Header = $category
$expander.IsExpanded = $true
$stackPanel = New-Object System.Windows.Controls.StackPanel
# Sort apps within the category alphabetically by content
$sortedApps = $appsByCategory[$category] | Sort-Object { $_.Value.content }
foreach ($app in $sortedApps) {
$checkBox = New-Object System.Windows.Controls.CheckBox
# StackPanel to hold the text and the hyperlink
$innerStackPanel = New-Object System.Windows.Controls.StackPanel
$innerStackPanel.Orientation = "Horizontal"
# TextBlock for the app's content
$textBlock = New-Object System.Windows.Controls.TextBlock
$textBlock.Text = $app.Value.content
$innerStackPanel.Children.Add($textBlock) | Out-Null
# ToolTip
$toolTip = New-Object System.Windows.Controls.ToolTip
$toolTip.Content = $app.Value.description
$checkBox.ToolTip = $app.Value.description
$checkBox.Content = $app.Value.content
$checkBox.Margin = New-Object System.Windows.Thickness(5)
$checkBox.Tag = @{ "choco" = $app.Value.choco; "winget" = $app.Value.winget }
#write-host $app.Value.choco
#write-host $app.Value.winget
$stackPanel.Children.Add($checkBox) | Out-Null
# Hyperlink
$hyperlink = New-Object System.Windows.Documents.Hyperlink
$hyperlink.Inlines.Add(" ?")
$hyperlink.NavigateUri = New-Object System.Uri($app.Value.link)
$hyperlink.Add_RequestNavigate({
param($sender, $e)
Start-Process $e.Uri.AbsoluteUri
})
$textBlock.Inlines.Add($hyperlink)
$hyperlink.TextDecorations = $null
}
$expander.Content = $stackPanel
$appspanel.Children.Add($expander) | Out-Null
}
}
# Window-level event handler for hyperlink clicks
$window.Add_PreviewMouseLeftButtonDown({
$pos = [Windows.Input.Mouse]::GetPosition($window)
$hitTestResult = [Windows.Media.VisualTreeHelper]::HitTest($window, $pos)
if ($hitTestResult -and $hitTestResult.VisualHit -is [System.Windows.Documents.Hyperlink]) {
$hyperlink = $hitTestResult.VisualHit
if ($hyperlink.NavigateUri) {
Start-Process $hyperlink.NavigateUri.AbsoluteUri
}
}
})
function Add-Source {
$newSource = $txtNewSource.Text
if (-not $newSource) { return } # Check if the new source is not empty
# Add the new source to the configuration file
Add-Content -Path "$directory\WinToolBox.config" -Value $newSource
# Create a new CheckBox for the new source
$checkbox = New-Object System.Windows.Controls.CheckBox
$checkbox.Content = $newSource
$checkbox.Margin = New-Object System.Windows.Thickness(5)
# Add the CheckBox to the StackPanel for sources
$panelSources.Children.Add($checkbox) | Out-Null
# Clear the input field after adding the source
$txtNewSource.Text = ""
}
function Remove-Source {
# Create an array to hold sources that will remain
$remainingSources = @()
# Iterate backwards through the StackPanel children because we'll be modifying the collection
for ($i = $panelSources.Children.Count - 1; $i -ge 0; $i--) {