mirror of
https://github.com/Raphire/Win11Debloat.git
synced 2026-06-10 02:26:29 +00:00
Compare commits
58 Commits
undo-tweak
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
893f32e1ed | ||
|
|
0d99fd6187 | ||
|
|
458305316e | ||
|
|
1b8b8ef615 | ||
|
|
226828325b | ||
|
|
d6e3b899b5 | ||
|
|
bf6b4d9e95 | ||
|
|
b6dfdab126 | ||
|
|
db24865051 | ||
|
|
1f73741da8 | ||
|
|
bfd06d953d | ||
|
|
8c654d4b88 | ||
|
|
2574e725bc | ||
|
|
30ad307bf4 | ||
|
|
c6b849408d | ||
|
|
4c4552c27d | ||
|
|
fe86388b5a | ||
|
|
275598e9aa | ||
|
|
506e901b60 | ||
|
|
377a1f6220 | ||
|
|
33b77f19a0 | ||
|
|
0c04709440 | ||
|
|
924772c3a0 | ||
|
|
68248b4a04 | ||
|
|
1ed967b9d3 | ||
|
|
4332eaa833 | ||
|
|
9deeb295e7 | ||
|
|
f6ed6ac487 | ||
|
|
b920536be2 | ||
|
|
7273f29fea | ||
|
|
7381c29da2 | ||
|
|
3bed9cafbc | ||
|
|
6dbaac0513 | ||
|
|
6e63b34dbb | ||
|
|
3f763b01ab | ||
|
|
4109588e0f | ||
|
|
37872b2030 | ||
|
|
abfc5db2c3 | ||
|
|
1d828d6a78 | ||
|
|
4d9da4749b | ||
|
|
5cf9ac4082 | ||
|
|
924c192ca5 | ||
|
|
2a5cb986c9 | ||
|
|
66982ada28 | ||
|
|
489af33a8b | ||
|
|
51aa288dfd | ||
|
|
24a6f1bcf8 | ||
|
|
8ac664e45f | ||
|
|
85aa67b5d2 | ||
|
|
c8b4563954 | ||
|
|
22f3144c0f | ||
|
|
2c360961e3 | ||
|
|
11a324365d | ||
|
|
5daa922148 | ||
|
|
1826d6d8be | ||
|
|
c15309bcf6 | ||
|
|
c1dc8f7ce3 | ||
|
|
ebb3a293d4 |
2
.github/CONTRIBUTING.md
vendored
2
.github/CONTRIBUTING.md
vendored
@@ -109,7 +109,7 @@ Avoid these common mistakes when contributing:
|
||||
|
||||
Placing files in the wrong directory will cause the script to fail when trying to apply or undo changes.
|
||||
|
||||
6. **Not Testing Undo Functionality**: Always test that your undo registry file properly reverts all changes. A feature that can't be undone will frustrate users.
|
||||
6. **Not Testing Undo Functionality**: Always test that your undo registry file properly reverts all changes.
|
||||
|
||||
7. **Not Testing User/Sysprep Functionality**: Always test that your feature works when applied to another user or to the Windows default user with Sysprep. Sysprep changes can be tested by creating new users after running the script.
|
||||
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -3,4 +3,5 @@ SavedSettings
|
||||
LastUsedSettings.json
|
||||
CustomAppsList
|
||||
Logs/*
|
||||
Win11Debloat.log
|
||||
Win11Debloat.log
|
||||
Backups/*
|
||||
@@ -781,9 +781,9 @@
|
||||
{
|
||||
"FriendlyName": "Windows Terminal",
|
||||
"AppId": "Microsoft.WindowsTerminal",
|
||||
"Description": "Default terminal app in windows 11 (Command Prompt, PowerShell, WSL)",
|
||||
"Description": "Default terminal app in windows 11 (Command Prompt, PowerShell, WSL), WARNING: Do not remove if you launched Win11Debloat from Windows Terminal, as this will cause the script to fail.",
|
||||
"SelectedByDefault": false,
|
||||
"Recommendation": "optional"
|
||||
"Recommendation": "unsafe"
|
||||
},
|
||||
{
|
||||
"FriendlyName": "Xbox TCUI Framework",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
7
Regfiles/Start_AllApps_Category.reg
Normal file
7
Regfiles/Start_AllApps_Category.reg
Normal file
@@ -0,0 +1,7 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Start]
|
||||
"AllAppsViewMode"=dword:00000000
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
|
||||
"NoStartMenuMorePrograms"=-
|
||||
7
Regfiles/Start_AllApps_Grid.reg
Normal file
7
Regfiles/Start_AllApps_Grid.reg
Normal file
@@ -0,0 +1,7 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Start]
|
||||
"AllAppsViewMode"=dword:00000001
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
|
||||
"NoStartMenuMorePrograms"=-
|
||||
7
Regfiles/Start_AllApps_List.reg
Normal file
7
Regfiles/Start_AllApps_List.reg
Normal file
@@ -0,0 +1,7 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Start]
|
||||
"AllAppsViewMode"=dword:00000002
|
||||
|
||||
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
|
||||
"NoStartMenuMorePrograms"=-
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
7
Regfiles/Sysprep/Start_AllApps_Category.reg
Normal file
7
Regfiles/Sysprep/Start_AllApps_Category.reg
Normal file
@@ -0,0 +1,7 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
[hkey_users\default\Software\Microsoft\Windows\CurrentVersion\Start]
|
||||
"AllAppsViewMode"=dword:00000000
|
||||
|
||||
[hkey_users\default\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
|
||||
"NoStartMenuMorePrograms"=-
|
||||
7
Regfiles/Sysprep/Start_AllApps_Grid.reg
Normal file
7
Regfiles/Sysprep/Start_AllApps_Grid.reg
Normal file
@@ -0,0 +1,7 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
[hkey_users\default\Software\Microsoft\Windows\CurrentVersion\Start]
|
||||
"AllAppsViewMode"=dword:00000001
|
||||
|
||||
[hkey_users\default\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
|
||||
"NoStartMenuMorePrograms"=-
|
||||
7
Regfiles/Sysprep/Start_AllApps_List.reg
Normal file
7
Regfiles/Sysprep/Start_AllApps_List.reg
Normal file
@@ -0,0 +1,7 @@
|
||||
Windows Registry Editor Version 5.00
|
||||
|
||||
[hkey_users\default\Software\Microsoft\Windows\CurrentVersion\Start]
|
||||
"AllAppsViewMode"=dword:00000002
|
||||
|
||||
[hkey_users\default\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer]
|
||||
"NoStartMenuMorePrograms"=-
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
6
Run.bat
6
Run.bat
@@ -19,15 +19,17 @@ if exist "%wtDefaultPath%" (
|
||||
set "wtPath="
|
||||
)
|
||||
|
||||
set "SCRIPT_PATH=\"%~dp0Win11Debloat.ps1\""
|
||||
|
||||
:: Launch script
|
||||
if defined wtPath (
|
||||
call :Log Launching Win11Debloat.ps1 with Windows Terminal...
|
||||
PowerShell -Command "Start-Process -FilePath '%wtPath%' -ArgumentList 'PowerShell -NoProfile -ExecutionPolicy Bypass -File ""%~dp0Win11Debloat.ps1""' -Verb RunAs" >> "%logFile%" || call :Error "PowerShell command failed"
|
||||
PowerShell -Command "Start-Process -FilePath '%wtPath%' -ArgumentList 'PowerShell -NoProfile -ExecutionPolicy Bypass -File %SCRIPT_PATH%' -Verb RunAs" >> "%logFile%" || call :Error "PowerShell command failed"
|
||||
call :Log Script execution passed successfully to Win11Debloat.ps1
|
||||
) else (
|
||||
echo Windows Terminal not found. Using default PowerShell instead...
|
||||
call :Log Windows Terminal not found. Using default PowerShell to launch Win11Debloat.ps1...
|
||||
PowerShell -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dp0Win11Debloat.ps1""' -Verb RunAs}" >> "%logFile%" || call :Error "PowerShell command failed"
|
||||
PowerShell -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File %SCRIPT_PATH%' -Verb RunAs}" >> "%logFile%" || call :Error "PowerShell command failed"
|
||||
call :Log Script execution passed successfully to Win11Debloat.ps1
|
||||
)
|
||||
|
||||
|
||||
@@ -11,18 +11,7 @@
|
||||
Topmost="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Border BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
Background="{DynamicResource CardBgColor}"
|
||||
Margin="25">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect Color="Black"
|
||||
Opacity="0.15"
|
||||
BlurRadius="20"
|
||||
ShadowDepth="0"
|
||||
Direction="0"/>
|
||||
</Border.Effect>
|
||||
<Border Style="{DynamicResource ModalCardBorderStyle}">
|
||||
|
||||
<Grid Margin="0">
|
||||
<Grid.RowDefinitions>
|
||||
@@ -32,13 +21,9 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Title Bar -->
|
||||
<Grid Grid.Row="0" x:Name="TitleBar" Height="48" Background="Transparent">
|
||||
<Grid Grid.Row="0" x:Name="TitleBar" Style="{DynamicResource ModalTitleBarStyle}">
|
||||
<TextBlock Text="About Win11Debloat"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontSize="18"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center"
|
||||
Margin="20,0,0,0"/>
|
||||
Style="{DynamicResource ModalTitleTextStyle}"/>
|
||||
</Grid>
|
||||
|
||||
<!-- Message Content -->
|
||||
@@ -50,7 +35,7 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Message Text -->
|
||||
<Grid Grid.Row="0" Margin="24,12,24,20">
|
||||
<Grid Grid.Row="0" Margin="20,4,20,20">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
@@ -62,43 +47,31 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Version -->
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="Version:"
|
||||
FontSize="14"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,16,8"/>
|
||||
<TextBlock Grid.Row="0" Grid.Column="0"
|
||||
Text="Version:"
|
||||
Style="{DynamicResource ModalInfoLabelTextStyle}"/>
|
||||
<TextBlock x:Name="VersionText"
|
||||
Grid.Row="0" Grid.Column="1"
|
||||
Text="0.0.0"
|
||||
FontSize="14"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Margin="0,0,0,8"/>
|
||||
Text="0.0.0"
|
||||
Style="{DynamicResource ModalInfoValueTextStyle}"/>
|
||||
|
||||
<!-- Author -->
|
||||
<TextBlock Grid.Row="1" Grid.Column="0"
|
||||
Text="Author:"
|
||||
FontSize="14"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,16,8"/>
|
||||
<TextBlock Grid.Row="1" Grid.Column="0"
|
||||
Text="Author:"
|
||||
Style="{DynamicResource ModalInfoLabelTextStyle}"/>
|
||||
<TextBlock Grid.Row="1" Grid.Column="1"
|
||||
Text="Raphire"
|
||||
FontSize="14"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Margin="0,0,0,8"/>
|
||||
Text="Raphire"
|
||||
Style="{DynamicResource ModalInfoValueTextStyle}"/>
|
||||
|
||||
<!-- Project Link -->
|
||||
<TextBlock Grid.Row="2" Grid.Column="0"
|
||||
Text="Project:"
|
||||
FontSize="14"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontWeight="SemiBold"
|
||||
<TextBlock Grid.Row="2" Grid.Column="0"
|
||||
Text="Project:"
|
||||
Style="{DynamicResource ModalInfoLabelTextStyle}"
|
||||
Margin="0,0,16,0"/>
|
||||
<TextBlock x:Name="ProjectLink"
|
||||
Grid.Row="2" Grid.Column="1"
|
||||
Text="https://github.com/Raphire/Win11Debloat"
|
||||
FontSize="14"
|
||||
FontSize="13"
|
||||
Style="{DynamicResource HyperlinkStyle}"
|
||||
Margin="0,0,0,0"/>
|
||||
</Grid>
|
||||
@@ -107,10 +80,10 @@
|
||||
<Border Grid.Row="1"
|
||||
Height="1"
|
||||
Background="{DynamicResource BorderColor}"
|
||||
Margin="10,0"/>
|
||||
Margin="20,0"/>
|
||||
|
||||
<!-- Content -->
|
||||
<StackPanel Grid.Row="2" Margin="24,20">
|
||||
<StackPanel Grid.Row="2" Margin="20,18,20,20">
|
||||
<!-- Donation Message -->
|
||||
<TextBlock Text="Win11Debloat is a passion project that I maintain in my free time. If you've found this tool useful, please consider making a small donation to support its development. I really appreciate it!"
|
||||
FontSize="14"
|
||||
@@ -150,19 +123,11 @@
|
||||
</Grid>
|
||||
|
||||
<!-- Button Panel -->
|
||||
<Border Grid.Row="2"
|
||||
Background="{DynamicResource BgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="16,12"
|
||||
CornerRadius="0,0,8,8">
|
||||
<StackPanel x:Name="ButtonPanel"
|
||||
Orientation="Horizontal"
|
||||
HorizontalAlignment="Right">
|
||||
<Border Grid.Row="2" Style="{DynamicResource ModalFooterBorderStyle}">
|
||||
<StackPanel x:Name="ButtonPanel" Style="{DynamicResource ModalFooterButtonsRightStyle}">
|
||||
<Button x:Name="CloseButton"
|
||||
Content="Close"
|
||||
Height="32" MinWidth="80" Margin="4,0"
|
||||
Style="{DynamicResource SecondaryButtonStyle}"/>
|
||||
Style="{DynamicResource ModalSecondaryActionButtonStyle}"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
|
||||
@@ -11,18 +11,7 @@
|
||||
Topmost="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Border BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
Background="{DynamicResource CardBgColor}"
|
||||
Margin="25">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect Color="Black"
|
||||
Opacity="0.15"
|
||||
BlurRadius="20"
|
||||
ShadowDepth="0"
|
||||
Direction="0"/>
|
||||
</Border.Effect>
|
||||
<Border Style="{DynamicResource ModalCardBorderStyle}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
@@ -100,11 +89,7 @@
|
||||
MaxWidth="430"/>
|
||||
</StackPanel>
|
||||
|
||||
<Border Background="{DynamicResource BgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="16,12"
|
||||
CornerRadius="0,0,8,8">
|
||||
<Border Style="{DynamicResource ModalFooterBorderStyle}">
|
||||
<StackPanel>
|
||||
|
||||
<!-- Progress bar -->
|
||||
@@ -172,17 +157,10 @@
|
||||
</Border>
|
||||
|
||||
<!-- Button Panel -->
|
||||
<Border Background="{DynamicResource BgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="16,12"
|
||||
CornerRadius="0,0,8,8">
|
||||
<StackPanel x:Name="ButtonPanel"
|
||||
Orientation="Horizontal"
|
||||
HorizontalAlignment="Center">
|
||||
<Border Style="{DynamicResource ModalFooterBorderStyle}">
|
||||
<UniformGrid x:Name="ButtonPanel" Rows="1">
|
||||
<Button x:Name="ApplyKofiBtn"
|
||||
Width="200" Height="32" Margin="4,0"
|
||||
Style="{DynamicResource SecondaryButtonStyle}"
|
||||
Style="{DynamicResource ModalSecondaryStretchedButtonStyle}"
|
||||
AutomationProperties.Name="Support the creator">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="14" VerticalAlignment="Center" Margin="0,0,8,-1"/>
|
||||
@@ -190,11 +168,11 @@
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button x:Name="ApplyCloseBtn"
|
||||
Content="Close"
|
||||
Width="200" Height="32" Margin="4,0"
|
||||
Style="{DynamicResource PrimaryButtonStyle}"
|
||||
AutomationProperties.Name="Close"/>
|
||||
</StackPanel>
|
||||
Style="{DynamicResource ModalPrimaryStretchedButtonStyle}"
|
||||
AutomationProperties.Name="Close">
|
||||
<TextBlock Text="Close" VerticalAlignment="Center" FontSize="14" Margin="0,0,0,1"/>
|
||||
</Button>
|
||||
</UniformGrid>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
|
||||
@@ -12,18 +12,7 @@
|
||||
Topmost="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Border BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
Background="{DynamicResource CardBgColor}"
|
||||
Margin="25">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect Color="Black"
|
||||
Opacity="0.15"
|
||||
BlurRadius="20"
|
||||
ShadowDepth="0"
|
||||
Direction="0"/>
|
||||
</Border.Effect>
|
||||
<Border Style="{DynamicResource ModalCardBorderStyle}">
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
@@ -33,18 +22,14 @@
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Title Bar -->
|
||||
<Grid Grid.Row="0" x:Name="TitleBar" Height="40" Background="Transparent">
|
||||
<Grid Grid.Row="0" x:Name="TitleBar" Style="{DynamicResource ModalTitleBarStyle}">
|
||||
<TextBlock x:Name="TitleText"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center"
|
||||
Margin="16,0,0,0"/>
|
||||
Style="{DynamicResource ModalTitleTextStyle}"/>
|
||||
</Grid>
|
||||
|
||||
<!-- Content -->
|
||||
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" Padding="0,0,8,0">
|
||||
<StackPanel x:Name="ContentPanel" Margin="20,12,20,9">
|
||||
<StackPanel x:Name="ContentPanel" Margin="20,4,20,8">
|
||||
<TextBlock x:Name="PromptText"
|
||||
TextWrapping="Wrap"
|
||||
FontSize="14"
|
||||
@@ -57,22 +42,15 @@
|
||||
</ScrollViewer>
|
||||
|
||||
<!-- Button Footer -->
|
||||
<Border Grid.Row="2"
|
||||
Background="{DynamicResource BgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="16,12"
|
||||
CornerRadius="0,0,8,8">
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
|
||||
<Border Grid.Row="2" Style="{DynamicResource ModalFooterBorderStyle}">
|
||||
<UniformGrid Rows="1">
|
||||
<Button x:Name="OkButton"
|
||||
Content="OK"
|
||||
Height="32" MinWidth="80" Margin="4,0"
|
||||
Style="{DynamicResource PrimaryButtonStyle}"/>
|
||||
Style="{DynamicResource ModalPrimaryStretchedButtonStyle}"/>
|
||||
<Button x:Name="CancelButton"
|
||||
Content="Cancel"
|
||||
Height="32" MinWidth="80" Margin="4,0"
|
||||
Style="{DynamicResource SecondaryButtonStyle}"/>
|
||||
</StackPanel>
|
||||
Style="{DynamicResource ModalSecondaryStretchedButtonStyle}"/>
|
||||
</UniformGrid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:shell="clr-namespace:System.Windows.Shell;assembly=PresentationFramework"
|
||||
Title="Win11Debloat"
|
||||
MinWidth="1130" MinHeight="600"
|
||||
MinWidth="860" MinHeight="600"
|
||||
ResizeMode="CanResize"
|
||||
SnapsToDevicePixels="True"
|
||||
WindowStartupLocation="CenterScreen"
|
||||
@@ -28,177 +28,6 @@
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- ComboBox Style -->
|
||||
<Style TargetType="ComboBox">
|
||||
<Setter Property="Background" Value="{DynamicResource ComboBgColor}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Margin" Value="0,4,0,12"/>
|
||||
<Setter Property="MinHeight" Value="33"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBox">
|
||||
<Grid>
|
||||
<!-- Left accent line -->
|
||||
<Border x:Name="ClosedAccentLine" Width="3" Height="18" HorizontalAlignment="Left" VerticalAlignment="Stretch" Background="{DynamicResource ButtonBg}" CornerRadius="1.5" Panel.ZIndex="2"/>
|
||||
<ToggleButton x:Name="ToggleButton" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Focusable="False" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press">
|
||||
<ToggleButton.Style>
|
||||
<Style TargetType="ToggleButton">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4">
|
||||
<TextBlock x:Name="Arrow"
|
||||
Text=""
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
FontSize="10"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,8,0"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
RenderTransformOrigin="0.5,0.5">
|
||||
<TextBlock.RenderTransform>
|
||||
<RotateTransform x:Name="ArrowRotation" Angle="0"/>
|
||||
</TextBlock.RenderTransform>
|
||||
</TextBlock>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Border" Property="Background" Value="{DynamicResource ComboHoverColor}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Trigger.EnterActions>
|
||||
<BeginStoryboard>
|
||||
<Storyboard>
|
||||
<DoubleAnimation Storyboard.TargetName="Arrow" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="180" Duration="0:0:0.2">
|
||||
<DoubleAnimation.EasingFunction>
|
||||
<CubicEase EasingMode="EaseOut"/>
|
||||
</DoubleAnimation.EasingFunction>
|
||||
</DoubleAnimation>
|
||||
</Storyboard>
|
||||
</BeginStoryboard>
|
||||
</Trigger.EnterActions>
|
||||
<Trigger.ExitActions>
|
||||
<BeginStoryboard>
|
||||
<Storyboard>
|
||||
<DoubleAnimation Storyboard.TargetName="Arrow" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="0" Duration="0:0:0.2">
|
||||
<DoubleAnimation.EasingFunction>
|
||||
<CubicEase EasingMode="EaseOut"/>
|
||||
</DoubleAnimation.EasingFunction>
|
||||
</DoubleAnimation>
|
||||
</Storyboard>
|
||||
</BeginStoryboard>
|
||||
</Trigger.ExitActions>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ToggleButton.Style>
|
||||
</ToggleButton>
|
||||
<ContentPresenter x:Name="ContentPresenter"
|
||||
IsHitTestVisible="False"
|
||||
Margin="10,0,20,0"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Content="{TemplateBinding SelectionBoxItem}"
|
||||
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
|
||||
ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
|
||||
<Popup x:Name="Popup"
|
||||
Placement="Bottom"
|
||||
IsOpen="{TemplateBinding IsDropDownOpen}"
|
||||
AllowsTransparency="True"
|
||||
Focusable="False"
|
||||
PopupAnimation="Fade"
|
||||
StaysOpen="False"
|
||||
PlacementTarget="{Binding ElementName=ToggleButton}"
|
||||
VerticalOffset="1"
|
||||
HorizontalOffset="0">
|
||||
<Grid x:Name="DropDown" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}" Margin="12">
|
||||
<Border x:Name="DropDownBorder"
|
||||
Background="{DynamicResource ComboItemBgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="4"
|
||||
Padding="5,4,5,1">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect BlurRadius="12" Opacity="0.25" ShadowDepth="4"/>
|
||||
</Border.Effect>
|
||||
<ScrollViewer Margin="0,2,0,0"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Disabled">
|
||||
<ItemsPresenter Margin="0,0,0,1"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Popup>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="SelectedIndex" Value="0">
|
||||
<Setter TargetName="ClosedAccentLine" Property="Visibility" Value="Collapsed"/>
|
||||
</Trigger>
|
||||
<Trigger Property="SelectedIndex" Value="-1">
|
||||
<Setter TargetName="ClosedAccentLine" Property="Visibility" Value="Collapsed"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="ClosedAccentLine" Property="Visibility" Value="Collapsed"/>
|
||||
<Setter Property="Background" Value="{DynamicResource ButtonDisabled}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonTextDisabled}"/>
|
||||
<Setter Property="Opacity" Value="0.6"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ComboBoxItem Style -->
|
||||
<Style TargetType="ComboBoxItem">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="Padding" Value="10,8"/>
|
||||
<Setter Property="Margin" Value="0,0,0,4"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBoxItem">
|
||||
<Grid>
|
||||
<Border x:Name="ItemBorder"
|
||||
Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
Padding="{TemplateBinding Padding}"
|
||||
CornerRadius="4">
|
||||
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
|
||||
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
|
||||
</Border>
|
||||
<!-- Left accent line -->
|
||||
<Border x:Name="AccentLine"
|
||||
Width="3"
|
||||
Height="15"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Stretch"
|
||||
Background="{DynamicResource ButtonBg}"
|
||||
CornerRadius="1.5"
|
||||
Margin="0"
|
||||
Visibility="Collapsed"/>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="AccentLine" Property="Visibility" Value="Visible"/>
|
||||
<Setter TargetName="ItemBorder" Property="Background" Value="{DynamicResource ComboItemSelectedColor}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsHighlighted" Value="True">
|
||||
<Setter TargetName="ItemBorder" Property="Background" Value="{DynamicResource ComboItemHoverColor}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- TextBlock Label Style -->
|
||||
<Style x:Key="LabelStyle" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
@@ -229,7 +58,7 @@
|
||||
<Style x:Key="CategoryHeaderTextBlock" TargetType="TextBlock">
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="FontSize" Value="16"/>
|
||||
<Setter Property="Margin" Value="0,0,0,13"/>
|
||||
<Setter Property="Margin" Value="0,0,0,12"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
</Style>
|
||||
|
||||
@@ -582,6 +411,11 @@
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="16" Foreground="{DynamicResource FgColor}"/>
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<MenuItem x:Name="RestoreBackupBtn" Header="Restore backup" AutomationProperties.Name="Restore registry backup">
|
||||
<MenuItem.Icon>
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="16" Foreground="{DynamicResource FgColor}"/>
|
||||
</MenuItem.Icon>
|
||||
</MenuItem>
|
||||
<Separator />
|
||||
<MenuItem x:Name="MenuDocumentation" Header="Documentation" AutomationProperties.Name="Documentation">
|
||||
<MenuItem.Icon>
|
||||
@@ -651,53 +485,81 @@
|
||||
<!-- Home Tab -->
|
||||
<TabItem Header="Home" x:Name="HomeTab">
|
||||
<Grid>
|
||||
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Width="600">
|
||||
<StackPanel x:Name="HomeContentPanel" HorizontalAlignment="Center" VerticalAlignment="Top">
|
||||
<!-- Logo -->
|
||||
<Viewbox Width="220" Height="220" Margin="0,32,0,10" HorizontalAlignment="Center">
|
||||
<Grid Width="220" Height="220">
|
||||
<Viewbox Width="250" Height="250" Margin="0,0,0,10" HorizontalAlignment="Center">
|
||||
<Grid Width="250" Height="250">
|
||||
<!-- Windows logo style icon -->
|
||||
<Path x:Name="LogoFallback" Data="M0,0 L80,0 L80,80 L0,80 Z M90,0 L170,0 L170,80 L90,80 Z M0,90 L80,90 L80,170 L0,170 Z M90,90 L170,90 L170,170 L90,170 Z"
|
||||
Fill="{DynamicResource ButtonBg}" Stretch="Uniform" Margin="10"/>
|
||||
<!-- Sparkle effects -->
|
||||
<Canvas HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="45" Height="45" Margin="0,0,2,2">
|
||||
<Canvas HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="50" Height="50" Margin="0,0,2,2">
|
||||
<Path Canvas.Left="10" Canvas.Top="16" Data="M12,0 L14,10 L24,12 L14,14 L12,24 L10,14 L0,12 L10,10 Z"
|
||||
Fill="{DynamicResource AccentColor}" Width="38" Height="38" Stretch="Uniform"/>
|
||||
Fill="{DynamicResource AccentColor}" Width="40" Height="40" Stretch="Uniform"/>
|
||||
<Path Canvas.Left="0" Canvas.Top="0" Data="M6,0 L7,5 L12,6 L7,7 L6,12 L5,7 L0,6 L5,5 Z"
|
||||
Fill="{DynamicResource AccentColor}" Width="20" Height="20" Stretch="Uniform"/>
|
||||
Fill="{DynamicResource AccentColor}" Width="22" Height="22" Stretch="Uniform"/>
|
||||
<Path Canvas.Left="35" Canvas.Top="8" Data="M4,0 L5,3 L8,4 L5,5 L4,8 L3,5 L0,4 L3,3 Z"
|
||||
Fill="{DynamicResource AccentColor}" Width="15" Height="15" Stretch="Uniform"/>
|
||||
Fill="{DynamicResource AccentColor}" Width="17" Height="17" Stretch="Uniform"/>
|
||||
</Canvas>
|
||||
<!-- Actual logo image if available -->
|
||||
<Image x:Name="LogoImage" Stretch="Uniform"/>
|
||||
</Grid>
|
||||
</Viewbox>
|
||||
|
||||
<!-- Title -->
|
||||
<TextBlock Text="Welcome to Win11Debloat" FontSize="28" FontWeight="Bold" Foreground="{DynamicResource FgColor}" HorizontalAlignment="Center" Margin="0,0,0,10"/>
|
||||
<TextBlock TextWrapping="Wrap" Foreground="{DynamicResource FgColor}" FontSize="16" LineHeight="22" HorizontalAlignment="Center" Margin="0,0,0,30">
|
||||
<TextBlock Text="Welcome to Win11Debloat" FontSize="30" FontWeight="Bold" Foreground="{DynamicResource FgColor}" HorizontalAlignment="Center" Margin="0,0,0,10"/>
|
||||
<TextBlock TextWrapping="Wrap" Foreground="{DynamicResource FgColor}" FontSize="18" LineHeight="22" HorizontalAlignment="Center" Margin="0,0,0,60">
|
||||
<Run Text="Your clean Windows experience is just a few clicks away!"/>
|
||||
</TextBlock>
|
||||
|
||||
<!-- Action Buttons -->
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,20,0,0">
|
||||
<Button x:Name="HomeDefaultModeBtn" Width="180" Height="50" Style="{DynamicResource PrimaryButtonStyle}" Margin="0,0,12,0" AutomationProperties.Name="Default Mode">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="16" VerticalAlignment="Center" Margin="0,0,8,0"/>
|
||||
<TextBlock Text="Default Mode" ToolTip="Quickly select the recommended settings" FontWeight="SemiBold" VerticalAlignment="Center" FontSize="17" Margin="0,0,0,2"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button x:Name="HomeStartBtn" Width="180" Height="50" Style="{DynamicResource SecondaryButtonStyle}" AutomationProperties.Name="Custom Setup">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="14" VerticalAlignment="Center" Margin="0,0,8,0"/>
|
||||
<TextBlock Text="Custom Setup" ToolTip="Manually select your preferred settings" FontWeight="SemiBold" VerticalAlignment="Center" FontSize="17" Margin="0,0,0,2"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
|
||||
<!-- Revert link -->
|
||||
<Button x:Name="HomeRevertLinkBtn" HorizontalAlignment="Center" Margin="0,11,0,0" Style="{DynamicResource ActionLinkButtonStyle}" AutomationProperties.Name="Revert previous changes">
|
||||
<TextBlock Text="Revert previous changes" Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
<Border HorizontalAlignment="Center" BorderBrush="{DynamicResource BorderColor}" BorderThickness="1" CornerRadius="4" Background="{DynamicResource CardBgColor}" Padding="16,12" Width="500">
|
||||
<StackPanel>
|
||||
<TextBlock Text="What user do you want to apply changes to?" Style="{StaticResource CategoryHeaderTextBlock}"/>
|
||||
<ComboBox x:Name="UserSelectionCombo" Margin="0,0,0,6" AutomationProperties.Name="Apply Changes To">
|
||||
<ComboBoxItem Content="Current User" IsSelected="True"/>
|
||||
<ComboBoxItem Content="Other User"/>
|
||||
<ComboBoxItem Content="Windows Default User (Sysprep)"/>
|
||||
</ComboBox>
|
||||
<StackPanel x:Name="OtherUserPanel" Visibility="Collapsed" Margin="0,0,0,6">
|
||||
<TextBlock x:Name="UsernameValidationMessage" Text="" FontStyle="Italic" Foreground="{DynamicResource CloseHover}" FontSize="11" Margin="3,0,0,4" TextWrapping="Wrap"/>
|
||||
<Border IsEnabled="{Binding ElementName=OtherUsernameTextBox, Path=IsEnabled}">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border" BasedOn="{StaticResource UserTextBoxBorderStyle}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ElementName=OtherUsernameTextBox, Path=IsFocused}" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource InputFocusColor}"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0" Text="" FontFamily="Segoe Fluent Icons" FontSize="14" VerticalAlignment="Center" Margin="4,0,8,0" Foreground="{DynamicResource FgColor}"/>
|
||||
<TextBlock x:Name="UsernameTextBoxPlaceholder" Grid.Column="1" Text="Enter username" Foreground="{DynamicResource FgColor}" Opacity="0.5" FontSize="13" Margin="3,0,0,1" VerticalAlignment="Center" IsHitTestVisible="False"/>
|
||||
<TextBox x:Name="OtherUsernameTextBox" Grid.Column="1" Style="{StaticResource UserTextBoxStyle}" Text="" AutomationProperties.Name="Enter username"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
|
||||
<Separator Margin="0,10,0,8" Background="{DynamicResource BorderColor}"/>
|
||||
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,8,0,0">
|
||||
<Button x:Name="HomeDefaultModeBtn" Width="227" Height="50" Style="{DynamicResource PrimaryButtonStyle}" Margin="0,0,12,0" AutomationProperties.Name="Default Mode">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="16" VerticalAlignment="Center" Margin="0,0,8,-1"/>
|
||||
<TextBlock Text="Default Mode" ToolTip="Quickly select the recommended settings" FontWeight="SemiBold" VerticalAlignment="Center" FontSize="17" Margin="0,0,0,1"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<Button x:Name="HomeStartBtn" Width="227" Height="50" Style="{DynamicResource SecondaryButtonStyle}" AutomationProperties.Name="Custom Setup">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="14" VerticalAlignment="Center" Margin="0,0,8,-1"/>
|
||||
<TextBlock Text="Custom Setup" ToolTip="Manually select your preferred settings" FontWeight="SemiBold" VerticalAlignment="Center" FontSize="17" Margin="0,0,0,1"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
@@ -903,6 +765,8 @@
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="10"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<StackPanel Grid.Column="0" Orientation="Horizontal">
|
||||
@@ -969,7 +833,9 @@
|
||||
</Popup>
|
||||
</StackPanel>
|
||||
|
||||
<Border x:Name="TweakSearchBorder" Grid.Column="2">
|
||||
<CheckBox x:Name="ShowCurrentlyAppliedTweaksCheckBox" Grid.Column="2" Content="Detect applied tweaks" IsChecked="True" Foreground="{DynamicResource FgColor}" VerticalAlignment="Center" AutomationProperties.Name="Detect applied tweaks" ToolTip="Detect all tweaks currently applied for the current user."/>
|
||||
|
||||
<Border x:Name="TweakSearchBorder" Grid.Column="4">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border" BasedOn="{StaticResource SearchBoxBorderStyle}">
|
||||
<Style.Triggers>
|
||||
@@ -1062,43 +928,15 @@
|
||||
<!-- Apply Changes To -->
|
||||
<Border Grid.Row="0" BorderBrush="{DynamicResource BorderColor}" BorderThickness="1" CornerRadius="4" Background="{DynamicResource CardBgColor}" Padding="16,12" Margin="0,0,0,16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Apply Changes To" Style="{StaticResource CategoryHeaderTextBlock}"/>
|
||||
<ComboBox x:Name="UserSelectionCombo" Margin="0,0,0,6" AutomationProperties.Name="Apply Changes To">
|
||||
<ComboBoxItem Content="Current User" IsSelected="True"/>
|
||||
<ComboBoxItem Content="Other User"/>
|
||||
<ComboBoxItem Content="Windows Default User (Sysprep)"/>
|
||||
</ComboBox>
|
||||
<StackPanel x:Name="OtherUserPanel" Visibility="Collapsed" Margin="0,0,0,6">
|
||||
<TextBlock x:Name="UsernameValidationMessage" Text="" FontStyle="Italic" Foreground="{DynamicResource CloseHover}" FontSize="11" Margin="3,0,0,4" TextWrapping="Wrap"/>
|
||||
<Border IsEnabled="{Binding ElementName=OtherUsernameTextBox, Path=IsEnabled}">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border" BasedOn="{StaticResource UserTextBoxBorderStyle}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding ElementName=OtherUsernameTextBox, Path=IsFocused}" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource InputFocusColor}"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0" Text="" FontFamily="Segoe Fluent Icons" FontSize="14" VerticalAlignment="Center" Margin="4,0,8,0" Foreground="{DynamicResource FgColor}"/>
|
||||
<TextBlock x:Name="UsernameTextBoxPlaceholder" Grid.Column="1" Text="Enter username" Foreground="{DynamicResource FgColor}" Opacity="0.5" FontSize="13" Margin="3,0,0,1" VerticalAlignment="Center" IsHitTestVisible="False"/>
|
||||
<TextBox x:Name="OtherUsernameTextBox" Grid.Column="1" Style="{StaticResource UserTextBoxStyle}" Text="" AutomationProperties.Name="Enter username"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="UserSelectionDescription" Text="Changes will be applied to the currently logged-in user profile." Foreground="{DynamicResource FgColor}" FontSize="12" TextWrapping="Wrap" Margin="0,6,0,3"/>
|
||||
<TextBlock Text="Changes will be applied to" Style="{StaticResource CategoryHeaderTextBlock}"/>
|
||||
<TextBlock x:Name="UserSelectionDescription" Text="The currently logged-in user profile." Foreground="{DynamicResource FgColor}" FontSize="12" TextWrapping="Wrap" Margin="0,0,0,3"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- App Removal Scope -->
|
||||
<Border Grid.Row="1" x:Name="AppRemovalScopeSection" BorderBrush="{DynamicResource BorderColor}" BorderThickness="1" CornerRadius="4" Background="{DynamicResource CardBgColor}" Padding="16,12" Margin="0,0,0,16">
|
||||
<StackPanel>
|
||||
<TextBlock Text="Remove Apps For" Style="{StaticResource CategoryHeaderTextBlock}"/>
|
||||
<TextBlock Text="Apps will be removed for" Style="{StaticResource CategoryHeaderTextBlock}"/>
|
||||
<ComboBox x:Name="AppRemovalScopeCombo" Margin="0,0,0,6" AutomationProperties.Name="App Removal Scope">
|
||||
<ComboBoxItem x:Name="AppRemovalScopeAllUsers" Content="All users" IsSelected="True"/>
|
||||
<ComboBoxItem x:Name="AppRemovalScopeCurrentUser" Content="Current user only"/>
|
||||
@@ -1149,8 +987,20 @@
|
||||
|
||||
<!-- Review & Apply Section -->
|
||||
<StackPanel Grid.Row="1" HorizontalAlignment="Stretch" Background="{DynamicResource BgColor}">
|
||||
<Button x:Name="ReviewChangesBtn" Style="{DynamicResource ActionLinkButtonStyle}" HorizontalAlignment="Center" Margin="0,4,0,10" AutomationProperties.Name="Review selected changes">
|
||||
<TextBlock Text="Review selected changes" Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
<Button x:Name="ReviewChangesBtn" Background="Transparent" BorderThickness="0" Cursor="Hand" HorizontalAlignment="Center" Margin="0,4,0,10" AutomationProperties.Name="Review selected changes">
|
||||
<Button.Template>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<TextBlock x:Name="LinkText" Text="Review selected changes" FontSize="14" Foreground="{DynamicResource ButtonBg}" FontWeight="SemiBold" HorizontalAlignment="Center"/>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="LinkText" Property="Foreground" Value="{DynamicResource ButtonHover}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="LinkText" Property="Foreground" Value="{DynamicResource ButtonPressed}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Button.Template>
|
||||
</Button>
|
||||
<Button x:Name="DeploymentApplyBtn" Style="{DynamicResource PrimaryButtonStyle}" Width="190" Height="44" HorizontalAlignment="Center" AutomationProperties.Name="Apply Changes">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
|
||||
@@ -44,34 +44,34 @@
|
||||
</Grid>
|
||||
|
||||
<!-- Message Content -->
|
||||
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" MaxHeight="500" Padding="0" Margin="20,12,1,20">
|
||||
<Grid Margin="0,0,20,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid Grid.Row="1" Margin="20,12,1,20">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Icon -->
|
||||
<TextBlock x:Name="IconText"
|
||||
Grid.Column="0"
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
FontSize="24"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="4,2,14,0"
|
||||
Visibility="Collapsed"/>
|
||||
<!-- Icon -->
|
||||
<TextBlock x:Name="IconText"
|
||||
Grid.Column="0"
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
FontSize="24"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="4,0,14,0"
|
||||
Visibility="Collapsed"/>
|
||||
|
||||
<!-- Message Text -->
|
||||
<!-- Message Text -->
|
||||
<ScrollViewer Grid.Column="1" VerticalScrollBarVisibility="Auto" MaxHeight="300" Padding="0">
|
||||
<TextBlock x:Name="MessageText"
|
||||
Grid.Column="1"
|
||||
Text="Message content goes here"
|
||||
TextWrapping="Wrap"
|
||||
FontSize="14"
|
||||
LineHeight="20"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,20,0"/>
|
||||
</ScrollViewer>
|
||||
</Grid>
|
||||
|
||||
<!-- Button Panel -->
|
||||
<Border Grid.Row="2"
|
||||
|
||||
427
Schemas/RestoreBackupWindow.xaml
Normal file
427
Schemas/RestoreBackupWindow.xaml
Normal file
@@ -0,0 +1,427 @@
|
||||
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="Restore Backup"
|
||||
Width="500"
|
||||
SizeToContent="Height"
|
||||
MaxHeight="560"
|
||||
ResizeMode="NoResize"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
WindowStyle="None"
|
||||
AllowsTransparency="True"
|
||||
Background="Transparent"
|
||||
Topmost="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Window.Resources>
|
||||
<Style x:Key="RestoreOptionTileStyle" TargetType="Button">
|
||||
<Setter Property="Background" Value="{DynamicResource SecondaryButtonBg}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderColor}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Padding" Value="12,10"/>
|
||||
<Setter Property="FontSize" Value="14"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="8"
|
||||
Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Left" VerticalAlignment="Center" Margin="0,0,0,1"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Background" Value="{DynamicResource SecondaryButtonDisabled}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource SecondaryButtonTextDisabled}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource SecondaryButtonHover}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderColor}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource SecondaryButtonPressed}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderColor}"/>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Border Style="{DynamicResource ModalCardBorderStyle}">
|
||||
<Grid Margin="0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid Grid.Row="0" x:Name="TitleBar" Style="{DynamicResource ModalTitleBarStyle}">
|
||||
<TextBlock x:Name="TitleText"
|
||||
Text="Restore Backup"
|
||||
Style="{DynamicResource ModalTitleTextStyle}"/>
|
||||
</Grid>
|
||||
|
||||
<Button x:Name="CloseBtn" Grid.Row="0"
|
||||
HorizontalAlignment="Right" VerticalAlignment="Top"
|
||||
Width="36" Height="32"
|
||||
BorderThickness="0"
|
||||
Cursor="Hand"
|
||||
ToolTip="Close"
|
||||
AutomationProperties.Name="Close">
|
||||
<Button.Template>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="{TemplateBinding Background}" BorderThickness="0" CornerRadius="0,8,0,0">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Button.Template>
|
||||
<Button.Style>
|
||||
<Style TargetType="Button">
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Background" Value="{DynamicResource CloseHover}"/>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Button.Style>
|
||||
<TextBlock Text="" FontFamily="Segoe Fluent Icons" FontSize="10"/>
|
||||
</Button>
|
||||
|
||||
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" Margin="0">
|
||||
<Grid Margin="20,4,20,18">
|
||||
|
||||
<TabControl x:Name="RestoreModeTabs"
|
||||
SelectedIndex="0"
|
||||
Background="Transparent"
|
||||
BorderThickness="0"
|
||||
Padding="0">
|
||||
<TabControl.ItemContainerStyle>
|
||||
<Style TargetType="TabItem">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
<Setter Property="Height" Value="0"/>
|
||||
</Style>
|
||||
</TabControl.ItemContainerStyle>
|
||||
<TabItem x:Name="SelectTypeTab" Header="SelectType">
|
||||
<Grid x:Name="SelectTypePanel">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0"
|
||||
TextWrapping="Wrap"
|
||||
FontSize="14"
|
||||
LineHeight="20"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Text="Choose what changes you want to restore."/>
|
||||
|
||||
<Button x:Name="ChooseRegistryBtn"
|
||||
Grid.Row="1"
|
||||
Margin="0,14,0,0"
|
||||
Style="{StaticResource RestoreOptionTileStyle}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0"
|
||||
Text=""
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
FontSize="24"
|
||||
VerticalAlignment="Center"
|
||||
Margin="14,0,14,0"/>
|
||||
<StackPanel Grid.Column="1"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,12,0">
|
||||
<TextBlock Text="Restore Registry Backup"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"/>
|
||||
<TextBlock Text="Restore system registry configuration from a backup"
|
||||
FontSize="12"
|
||||
Opacity="0.75"
|
||||
TextWrapping="Wrap"
|
||||
Margin="0,2,0,0"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Button>
|
||||
|
||||
<Button x:Name="ChooseStartMenuBtn"
|
||||
Grid.Row="2"
|
||||
Margin="0,10,0,0"
|
||||
Style="{StaticResource RestoreOptionTileStyle}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0"
|
||||
Text=""
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
FontSize="24"
|
||||
VerticalAlignment="Center"
|
||||
Margin="14,0,14,0"/>
|
||||
<StackPanel Grid.Column="1"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,12,0">
|
||||
<TextBlock Text="Restore Start Menu Backup"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"/>
|
||||
<TextBlock Text="Restore the Start Menu pinned apps layout from a backup"
|
||||
FontSize="12"
|
||||
Opacity="0.75"
|
||||
TextWrapping="Wrap"
|
||||
Margin="0,2,0,0"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Button>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<TabItem x:Name="RegistryTab" Header="Registry">
|
||||
<Grid x:Name="RegistryPanel">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid x:Name="IntroInfoPanel" Grid.Row="0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0"
|
||||
TextWrapping="Wrap"
|
||||
FontSize="14"
|
||||
LineHeight="20"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Text="This will restore any system registry changes made by Win11Debloat to their previous state. You can review the changes after selecting a backup file. Apps will need to be reinstalled manually."/>
|
||||
|
||||
<TextBlock Grid.Row="1"
|
||||
Margin="0,12,0,2"
|
||||
TextWrapping="Wrap"
|
||||
FontSize="13"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Opacity="0.75"
|
||||
Text="Warning: Only use backup files generated by Win11Debloat."/>
|
||||
</Grid>
|
||||
|
||||
<Grid x:Name="OverviewPanel" Grid.Row="1" Margin="0" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid Grid.Row="0" Margin="0,0,0,16">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" Grid.Column="0" Text="File:" Style="{DynamicResource ModalInfoLabelTextStyle}"/>
|
||||
<TextBlock x:Name="BackupFileText" Grid.Row="0" Grid.Column="1" Text="Not selected" Style="{DynamicResource ModalInfoValueTextStyle}" TextWrapping="Wrap" Margin="0,0,0,8"/>
|
||||
|
||||
<TextBlock Grid.Row="1" Grid.Column="0" Text="Created:" Style="{DynamicResource ModalInfoLabelTextStyle}"/>
|
||||
<TextBlock x:Name="BackupCreatedText" Grid.Row="1" Grid.Column="1" Text="N/A" Style="{DynamicResource ModalInfoValueTextStyle}"/>
|
||||
|
||||
<TextBlock Grid.Row="2" Grid.Column="0" Text="Target:" Style="{DynamicResource ModalInfoLabelTextStyle}" Margin="0,0,16,0"/>
|
||||
<TextBlock x:Name="BackupTargetText" Grid.Row="2" Grid.Column="1" Text="N/A" Style="{DynamicResource ModalInfoValueTextStyle}" Margin="0"/>
|
||||
</Grid>
|
||||
|
||||
<Border Grid.Row="1" Height="1" Background="{DynamicResource BorderColor}" Margin="0,0,0,12"/>
|
||||
|
||||
<Grid x:Name="OverviewFeaturesSection" Grid.Row="2">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="The following changes will be reverted:"
|
||||
FontSize="13"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,0,8"/>
|
||||
|
||||
<ItemsControl x:Name="FeaturesItemsControl" Grid.Row="1">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Vertical" IsItemsHost="True"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding DisplayText}" FontSize="12" Foreground="{DynamicResource FgColor}" TextWrapping="Wrap" Margin="0,0,0,6"/>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
|
||||
<TextBlock x:Name="OverviewSummaryText"
|
||||
Grid.Row="2"
|
||||
FontSize="13"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
TextWrapping="Wrap"
|
||||
Visibility="Collapsed"
|
||||
Text="This will restore the Start Menu pinned apps layout for the current user."/>
|
||||
|
||||
<Border x:Name="ReappliedSeparator" Grid.Row="3" Height="1" Background="{DynamicResource BorderColor}" Margin="0,12,0,12" Visibility="Collapsed"/>
|
||||
|
||||
<Grid x:Name="ReappliedPanel" Grid.Row="4" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="The following changes will be re-applied:"
|
||||
FontSize="13"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,0,8"/>
|
||||
|
||||
<ItemsControl x:Name="ReappliedFeaturesItemsControl" Grid.Row="1">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Vertical" IsItemsHost="True"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding DisplayText}" FontSize="12" Foreground="{DynamicResource FgColor}" TextWrapping="Wrap" Margin="0,0,0,6"/>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
|
||||
<Border x:Name="NonRevertibleSeparator" Grid.Row="5" Height="1" Background="{DynamicResource BorderColor}" Margin="0,12,0,12" Visibility="Collapsed"/>
|
||||
|
||||
<Grid x:Name="NonRevertiblePanel" Grid.Row="6" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="The following changes won't be reverted:"
|
||||
FontSize="13"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontWeight="SemiBold"
|
||||
Margin="0,0,0,8"/>
|
||||
|
||||
<ItemsControl x:Name="NonRevertibleFeaturesItemsControl" Grid.Row="1">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<StackPanel Orientation="Vertical" IsItemsHost="True"/>
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding DisplayText}" FontSize="12" Foreground="{DynamicResource FgColor}" Opacity="0.85" TextWrapping="Wrap" Margin="0,0,0,6"/>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
|
||||
<TextBlock x:Name="NonRevertibleWikiLink"
|
||||
Grid.Row="2"
|
||||
Margin="0,8,0,0"
|
||||
Text="Visit the wiki for more information"
|
||||
FontSize="13"
|
||||
FontWeight="SemiBold"
|
||||
Style="{DynamicResource HyperlinkStyle}"
|
||||
TextWrapping="Wrap"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<TabItem x:Name="StartMenuTab" Header="StartMenu">
|
||||
<Grid x:Name="StartMenuPanel">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid x:Name="StartMenuIntroPanel" Grid.Row="0" Visibility="Visible">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0"
|
||||
TextWrapping="Wrap"
|
||||
FontSize="14"
|
||||
LineHeight="20"
|
||||
Margin="0,0,0,12"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Text="This will restore the Start Menu pinned apps layout for the selected user(s) using a backup. Win11Debloat can automatically find the backup created by the script."/>
|
||||
|
||||
<ComboBox x:Name="StartMenuScopeCombo"
|
||||
Grid.Row="1"
|
||||
SelectedIndex="0"
|
||||
Margin="0,0,0,2"
|
||||
MinWidth="408"
|
||||
HorizontalAlignment="Left">
|
||||
<ComboBoxItem Content="Current user" Tag="CurrentUser"/>
|
||||
<ComboBoxItem Content="All users" Tag="AllUsers"/>
|
||||
</ComboBox>
|
||||
|
||||
<CheckBox x:Name="StartMenuAutoBackupCheck"
|
||||
Grid.Row="2"
|
||||
Content="Automatically find Start Menu backup"
|
||||
IsChecked="True"
|
||||
FontSize="12"
|
||||
Margin="0,10,0,0"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
Opacity="0.85"/>
|
||||
</Grid>
|
||||
|
||||
</Grid>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
</ScrollViewer>
|
||||
|
||||
<Border Grid.Row="3" Style="{DynamicResource ModalFooterBorderStyle}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<Button x:Name="PrimaryActionBtn"
|
||||
Grid.Column="0"
|
||||
Content="Next"
|
||||
Visibility="Collapsed"
|
||||
Style="{DynamicResource ModalPrimaryStretchedButtonStyle}"/>
|
||||
|
||||
<Button x:Name="BackBtn"
|
||||
Grid.Column="1"
|
||||
Content="Back"
|
||||
Visibility="Collapsed"
|
||||
Style="{DynamicResource ModalSecondaryStretchedButtonStyle}"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
@@ -1,160 +0,0 @@
|
||||
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="Revert Changes"
|
||||
Width="620"
|
||||
Height="620"
|
||||
MinWidth="560"
|
||||
MinHeight="420"
|
||||
ResizeMode="CanResize"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
WindowStyle="None"
|
||||
AllowsTransparency="True"
|
||||
Background="Transparent"
|
||||
Topmost="False"
|
||||
ShowInTaskbar="False">
|
||||
|
||||
<Window.Resources>
|
||||
<Style x:Key="RevertItemBorderStyle" TargetType="Border">
|
||||
<Setter Property="BorderThickness" Value="0,0,0,1"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="Padding" Value="4,6,4,6"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="RevertItemRowStyle" TargetType="StackPanel">
|
||||
<Setter Property="Orientation" Value="Vertical"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="RevertItemUndoTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="Opacity" Value="0.75"/>
|
||||
<Setter Property="Margin" Value="26,-8,0,3"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
<Setter Property="TextWrapping" Value="Wrap"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="RevertEmptyTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="Opacity" Value="0.85"/>
|
||||
<Setter Property="Margin" Value="6,0,6,0"/>
|
||||
<Setter Property="TextWrapping" Value="Wrap"/>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Border BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="8"
|
||||
Background="{DynamicResource CardBgColor}"
|
||||
Margin="25">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect Color="Black"
|
||||
Opacity="0.15"
|
||||
BlurRadius="20"
|
||||
ShadowDepth="0"
|
||||
Direction="0"/>
|
||||
</Border.Effect>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid Grid.Row="0" x:Name="TitleBar" Height="40" Background="Transparent">
|
||||
<TextBlock x:Name="TitleText"
|
||||
Text="Revert Changes"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
FontSize="16"
|
||||
FontWeight="SemiBold"
|
||||
VerticalAlignment="Center"
|
||||
Margin="16,0,0,0"/>
|
||||
</Grid>
|
||||
|
||||
<StackPanel Grid.Row="1" Margin="20,12,1,12">
|
||||
<TextBlock x:Name="MessageText"
|
||||
Grid.Column="1"
|
||||
Text="Select which previously applied tweaks should be reverted to Windows defaults."
|
||||
TextWrapping="Wrap"
|
||||
FontSize="14"
|
||||
LineHeight="20"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
|
||||
<Grid Grid.Row="2" Margin="20,0,20,10">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<DockPanel Grid.Row="0" Margin="0,0,0,8">
|
||||
<StackPanel Orientation="Horizontal" DockPanel.Dock="Left">
|
||||
<Button x:Name="RevertSelectAllBtn"
|
||||
Content="Select All"
|
||||
Height="30"
|
||||
Padding="12,0"
|
||||
Style="{DynamicResource SecondaryButtonStyle}"
|
||||
Margin="0,0,8,0"
|
||||
AutomationProperties.Name="Select All"/>
|
||||
<Button x:Name="RevertClearBtn"
|
||||
Content="Clear"
|
||||
Height="30"
|
||||
Padding="12,0"
|
||||
Style="{DynamicResource SecondaryButtonStyle}"
|
||||
AutomationProperties.Name="Clear"/>
|
||||
</StackPanel>
|
||||
<TextBlock x:Name="RevertSelectionCount"
|
||||
Text="0 settings selected"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
VerticalAlignment="Center"
|
||||
HorizontalAlignment="Right"
|
||||
DockPanel.Dock="Right"
|
||||
Margin="0,0,6,0"/>
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Row="1"
|
||||
BorderThickness="1"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
CornerRadius="6"
|
||||
Background="{DynamicResource BgColor}">
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Padding="8" Margin="0,1,1,1">
|
||||
<StackPanel x:Name="RevertItemsPanel"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
|
||||
<CheckBox x:Name="RevertRestartExplorerCheckBox"
|
||||
Grid.Row="2"
|
||||
Content="Restart the Windows Explorer process to apply all changes immediately"
|
||||
IsChecked="False"
|
||||
Margin="2,10,0,0"
|
||||
AutomationProperties.Name="Restart the Windows Explorer process to apply all changes immediately"/>
|
||||
</Grid>
|
||||
|
||||
<!-- Button Panel -->
|
||||
<Border Grid.Row="3"
|
||||
Background="{DynamicResource BgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="0,1,0,0"
|
||||
Padding="16,12"
|
||||
CornerRadius="0,0,8,8">
|
||||
<StackPanel x:Name="ButtonPanel"
|
||||
Orientation="Horizontal"
|
||||
HorizontalAlignment="Right">
|
||||
<Button x:Name="RevertApplyBtn"
|
||||
Content="Revert Selected Settings"
|
||||
Height="32" MinWidth="200" Margin="4,0"
|
||||
Style="{DynamicResource PrimaryButtonStyle}"
|
||||
IsEnabled="False"
|
||||
AutomationProperties.Name="Revert Selected Settings"/>
|
||||
<Button x:Name="RevertCancelBtn"
|
||||
Content="Cancel"
|
||||
Height="32" MinWidth="80" Margin="4,0"
|
||||
Style="{DynamicResource SecondaryButtonStyle}"
|
||||
AutomationProperties.Name="Cancel"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Window>
|
||||
@@ -90,32 +90,6 @@
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- Shared link-style button used for text actions like review/revert links -->
|
||||
<Style x:Key="ActionLinkButtonStyle" TargetType="Button">
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="BorderThickness" Value="0"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonBg}"/>
|
||||
<Setter Property="FontSize" Value="14"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Padding" Value="0"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonHover}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonPressed}"/>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- ProgressBar Style -->
|
||||
<Style x:Key="ApplyProgressBarStyle" TargetType="ProgressBar">
|
||||
<Setter Property="Background" Value="{DynamicResource ButtonBorderColor}"/>
|
||||
@@ -151,6 +125,255 @@
|
||||
<Setter Property="TextAlignment" Value="Center"/>
|
||||
</Style>
|
||||
|
||||
<!-- Shared modal window shell styles -->
|
||||
<Style x:Key="ModalCardBorderStyle" TargetType="Border">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="CornerRadius" Value="8"/>
|
||||
<Setter Property="Background" Value="{DynamicResource CardBgColor}"/>
|
||||
<Setter Property="Margin" Value="25"/>
|
||||
<Setter Property="Effect">
|
||||
<Setter.Value>
|
||||
<DropShadowEffect Color="Black"
|
||||
Opacity="0.15"
|
||||
BlurRadius="20"
|
||||
ShadowDepth="0"
|
||||
Direction="0"/>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalTitleBarStyle" TargetType="Grid">
|
||||
<Setter Property="Height" Value="48"/>
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalTitleTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="FontSize" Value="16"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
<Setter Property="Margin" Value="20,0,0,0"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalFooterBorderStyle" TargetType="Border">
|
||||
<Setter Property="Background" Value="{DynamicResource BgColor}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="BorderThickness" Value="0,1,0,0"/>
|
||||
<Setter Property="Padding" Value="16,12"/>
|
||||
<Setter Property="CornerRadius" Value="0,0,8,8"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalFooterButtonsRightStyle" TargetType="StackPanel">
|
||||
<Setter Property="Orientation" Value="Horizontal"/>
|
||||
<Setter Property="HorizontalAlignment" Value="Right"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalPrimaryActionButtonStyle" TargetType="Button" BasedOn="{StaticResource PrimaryButtonStyle}">
|
||||
<Setter Property="Height" Value="32"/>
|
||||
<Setter Property="MinWidth" Value="80"/>
|
||||
<Setter Property="Margin" Value="4,0"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalSecondaryActionButtonStyle" TargetType="Button" BasedOn="{StaticResource SecondaryButtonStyle}">
|
||||
<Setter Property="Height" Value="32"/>
|
||||
<Setter Property="MinWidth" Value="80"/>
|
||||
<Setter Property="Margin" Value="4,0"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalPrimaryStretchedButtonStyle" TargetType="Button" BasedOn="{StaticResource PrimaryButtonStyle}">
|
||||
<Setter Property="Height" Value="32"/>
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch"/>
|
||||
<Setter Property="Margin" Value="4,0"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalSecondaryStretchedButtonStyle" TargetType="Button" BasedOn="{StaticResource SecondaryButtonStyle}">
|
||||
<Setter Property="Height" Value="32"/>
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch"/>
|
||||
<Setter Property="Margin" Value="4,0"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalInfoLabelTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="FontWeight" Value="SemiBold"/>
|
||||
<Setter Property="Margin" Value="0,0,16,8"/>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ModalInfoValueTextStyle" TargetType="TextBlock">
|
||||
<Setter Property="FontSize" Value="13"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="Margin" Value="0,0,0,8"/>
|
||||
</Style>
|
||||
|
||||
<!-- Shared ComboBox style used across windows -->
|
||||
<Style TargetType="ComboBoxItem">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Setter Property="Padding" Value="10,8"/>
|
||||
<Setter Property="Margin" Value="0,0,0,4"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBoxItem">
|
||||
<Grid>
|
||||
<Border x:Name="ItemBorder"
|
||||
Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
Padding="{TemplateBinding Padding}"
|
||||
CornerRadius="4">
|
||||
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
|
||||
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
|
||||
</Border>
|
||||
<Border x:Name="AccentLine"
|
||||
Width="3"
|
||||
Height="15"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Stretch"
|
||||
Background="{DynamicResource ButtonBg}"
|
||||
CornerRadius="1.5"
|
||||
Margin="0"
|
||||
Visibility="Collapsed"/>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="AccentLine" Property="Visibility" Value="Visible"/>
|
||||
<Setter TargetName="ItemBorder" Property="Background" Value="{DynamicResource ComboItemSelectedColor}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsHighlighted" Value="True">
|
||||
<Setter TargetName="ItemBorder" Property="Background" Value="{DynamicResource ComboItemHoverColor}"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="ComboBox">
|
||||
<Setter Property="Background" Value="{DynamicResource ComboBgColor}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Margin" Value="0,4,0,12"/>
|
||||
<Setter Property="MinHeight" Value="33"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ComboBox">
|
||||
<Grid>
|
||||
<Border x:Name="ClosedAccentLine" Width="3" Height="18" HorizontalAlignment="Left" VerticalAlignment="Stretch" Background="{DynamicResource ButtonBg}" CornerRadius="1.5" Panel.ZIndex="2"/>
|
||||
<ToggleButton x:Name="ToggleButton" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Focusable="False" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press">
|
||||
<ToggleButton.Style>
|
||||
<Style TargetType="ToggleButton">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ToggleButton">
|
||||
<Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="4">
|
||||
<TextBlock x:Name="Arrow"
|
||||
Text=""
|
||||
FontFamily="Segoe Fluent Icons"
|
||||
FontSize="10"
|
||||
HorizontalAlignment="Right"
|
||||
VerticalAlignment="Center"
|
||||
Margin="0,0,8,0"
|
||||
Foreground="{DynamicResource FgColor}"
|
||||
RenderTransformOrigin="0.5,0.5">
|
||||
<TextBlock.RenderTransform>
|
||||
<RotateTransform Angle="0"/>
|
||||
</TextBlock.RenderTransform>
|
||||
</TextBlock>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Border" Property="Background" Value="{DynamicResource ComboHoverColor}"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Trigger.EnterActions>
|
||||
<BeginStoryboard>
|
||||
<Storyboard>
|
||||
<DoubleAnimation Storyboard.TargetName="Arrow" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="180" Duration="0:0:0.2">
|
||||
<DoubleAnimation.EasingFunction>
|
||||
<CubicEase EasingMode="EaseOut"/>
|
||||
</DoubleAnimation.EasingFunction>
|
||||
</DoubleAnimation>
|
||||
</Storyboard>
|
||||
</BeginStoryboard>
|
||||
</Trigger.EnterActions>
|
||||
<Trigger.ExitActions>
|
||||
<BeginStoryboard>
|
||||
<Storyboard>
|
||||
<DoubleAnimation Storyboard.TargetName="Arrow" Storyboard.TargetProperty="(UIElement.RenderTransform).(RotateTransform.Angle)" To="0" Duration="0:0:0.2">
|
||||
<DoubleAnimation.EasingFunction>
|
||||
<CubicEase EasingMode="EaseOut"/>
|
||||
</DoubleAnimation.EasingFunction>
|
||||
</DoubleAnimation>
|
||||
</Storyboard>
|
||||
</BeginStoryboard>
|
||||
</Trigger.ExitActions>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ToggleButton.Style>
|
||||
</ToggleButton>
|
||||
<ContentPresenter x:Name="ContentPresenter"
|
||||
IsHitTestVisible="False"
|
||||
Margin="10,0,20,0"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Content="{TemplateBinding SelectionBoxItem}"
|
||||
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
|
||||
ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"/>
|
||||
<Popup x:Name="Popup"
|
||||
Placement="Bottom"
|
||||
IsOpen="{TemplateBinding IsDropDownOpen}"
|
||||
AllowsTransparency="True"
|
||||
Focusable="False"
|
||||
PopupAnimation="Fade"
|
||||
StaysOpen="False"
|
||||
PlacementTarget="{Binding ElementName=ToggleButton}"
|
||||
VerticalOffset="1"
|
||||
HorizontalOffset="0">
|
||||
<Grid x:Name="DropDown" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}" Margin="12">
|
||||
<Border x:Name="DropDownBorder"
|
||||
Background="{DynamicResource ComboItemBgColor}"
|
||||
BorderBrush="{DynamicResource BorderColor}"
|
||||
BorderThickness="1"
|
||||
CornerRadius="4"
|
||||
Padding="5,4,5,1">
|
||||
<Border.Effect>
|
||||
<DropShadowEffect BlurRadius="12" Opacity="0.25" ShadowDepth="4"/>
|
||||
</Border.Effect>
|
||||
<ScrollViewer Margin="0,2,0,0"
|
||||
VerticalScrollBarVisibility="Auto"
|
||||
HorizontalScrollBarVisibility="Disabled">
|
||||
<ItemsPresenter Margin="0,0,0,1"/>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Popup>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="SelectedIndex" Value="0">
|
||||
<Setter TargetName="ClosedAccentLine" Property="Visibility" Value="Collapsed"/>
|
||||
</Trigger>
|
||||
<Trigger Property="SelectedIndex" Value="-1">
|
||||
<Setter TargetName="ClosedAccentLine" Property="Visibility" Value="Collapsed"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter TargetName="ClosedAccentLine" Property="Visibility" Value="Collapsed"/>
|
||||
<Setter Property="Background" Value="{DynamicResource ButtonDisabled}"/>
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource BorderColor}"/>
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonTextDisabled}"/>
|
||||
<Setter Property="Opacity" Value="0.6"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Base CheckBox style used across windows -->
|
||||
<Style TargetType="CheckBox">
|
||||
<Setter Property="Foreground" Value="{DynamicResource FgColor}"/>
|
||||
|
||||
@@ -1,33 +1,14 @@
|
||||
# Prints all pending changes that will be made by the script
|
||||
function PrintPendingChanges {
|
||||
$skippedParams = @()
|
||||
$undoChanges = $script:Params.ContainsKey('Undo')
|
||||
|
||||
if ($undoChanges) {
|
||||
Write-Output "Win11Debloat will make the following changes to revert the selected settings to Windows defaults:"
|
||||
}
|
||||
else {
|
||||
Write-Output "Win11Debloat will make the following changes:"
|
||||
}
|
||||
Write-Output "Win11Debloat will make the following changes:"
|
||||
|
||||
if ($script:Params['CreateRestorePoint']) {
|
||||
Write-Output "- $($script:Features['CreateRestorePoint'].Action)"
|
||||
Write-Output "- $($script:Features['CreateRestorePoint'].Label)"
|
||||
}
|
||||
foreach ($parameterName in $script:Params.Keys) {
|
||||
if ($script:ControlParams -contains $parameterName) {
|
||||
continue
|
||||
}
|
||||
if ($parameterName -eq 'Apps' -or $parameterName -eq 'CreateRestorePoint') {
|
||||
continue
|
||||
}
|
||||
|
||||
if ($undoChanges) {
|
||||
$undoFeature = GetUndoFeatureForParam -paramKey $parameterName
|
||||
if (-not $undoFeature) {
|
||||
$skippedParams += $parameterName
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
# Print parameter description
|
||||
switch ($parameterName) {
|
||||
@@ -65,18 +46,8 @@ function PrintPendingChanges {
|
||||
}
|
||||
default {
|
||||
if ($script:Features -and $script:Features.ContainsKey($parameterName)) {
|
||||
$message = if ($undoChanges -and $script:Features[$parameterName].UndoAction) {
|
||||
$script:Features[$parameterName].UndoAction
|
||||
}
|
||||
else {
|
||||
$script:Features[$parameterName].Action
|
||||
}
|
||||
if ($message) {
|
||||
Write-Output "- $message"
|
||||
}
|
||||
else {
|
||||
Write-Output "- $parameterName"
|
||||
}
|
||||
$message = $script:Features[$parameterName].Label
|
||||
Write-Output "- $message"
|
||||
}
|
||||
else {
|
||||
# Fallback: show the parameter name if no feature description is available
|
||||
@@ -87,18 +58,8 @@ function PrintPendingChanges {
|
||||
}
|
||||
}
|
||||
|
||||
if ($undoChanges -and $skippedParams.Count -gt 0) {
|
||||
Write-Output ""
|
||||
Write-Output "The following changes cannot be automatically undone and will be skipped:"
|
||||
|
||||
$uniqueSkipped = $skippedParams | Sort-Object -Unique
|
||||
foreach ($skippedParam in $uniqueSkipped) {
|
||||
Write-Output "- $($script:Features[$skippedParam].Action)"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
Write-Output ""
|
||||
Write-Output "Press enter to execute the script or press CTRL+C to quit..."
|
||||
Read-Host | Out-Null
|
||||
}
|
||||
}
|
||||
21
Scripts/Features/BackupRegistryFeatureSelection.ps1
Normal file
21
Scripts/Features/BackupRegistryFeatureSelection.ps1
Normal file
@@ -0,0 +1,21 @@
|
||||
function Get-FeatureId {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Feature
|
||||
)
|
||||
|
||||
$featureId = [string]$Feature.FeatureId
|
||||
if ([string]::IsNullOrWhiteSpace($featureId)) {
|
||||
throw 'Selected feature is missing required FeatureId.'
|
||||
}
|
||||
|
||||
return $featureId
|
||||
}
|
||||
|
||||
function Get-RegistryBackedFeatures {
|
||||
param(
|
||||
[object[]]$Features = @()
|
||||
)
|
||||
|
||||
return @($Features | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_.RegistryKey) })
|
||||
}
|
||||
302
Scripts/Features/BackupRegistrySnapshotCapture.ps1
Normal file
302
Scripts/Features/BackupRegistrySnapshotCapture.ps1
Normal file
@@ -0,0 +1,302 @@
|
||||
function Get-RegistryBackupCapturePlans {
|
||||
param(
|
||||
[object[]]$SelectedRegistryFeatures = @(),
|
||||
[object[]]$UndoRegistryFeatures = @(),
|
||||
[switch]$UseSysprepRegFiles
|
||||
)
|
||||
|
||||
$planMap = @{}
|
||||
|
||||
foreach ($feature in $SelectedRegistryFeatures) {
|
||||
$regFilePath = Get-RegistryFilePathForFeature -RegistryKey $feature.RegistryKey -UseSysprepRegFiles:$UseSysprepRegFiles
|
||||
if (-not (Test-Path $regFilePath)) {
|
||||
throw "Unable to find registry file for backup: $($feature.RegistryKey) ($regFilePath)"
|
||||
}
|
||||
|
||||
foreach ($operation in @(Get-RegFileOperations -regFilePath $regFilePath)) {
|
||||
if (-not $operation.KeyPath) { continue }
|
||||
Add-RegistryPlanOperation -PlanMap $planMap -Operation $operation
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($feature in $UndoRegistryFeatures) {
|
||||
$regFilePath = Resolve-RegistryBackupUndoFilePath -Feature $feature
|
||||
if ([string]::IsNullOrWhiteSpace($regFilePath)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not (Test-Path $regFilePath)) {
|
||||
$undoKeyDescription = if (-not [string]::IsNullOrWhiteSpace([string]$feature.RegistryUndoKey)) {
|
||||
[string]$feature.RegistryUndoKey
|
||||
}
|
||||
else {
|
||||
[string]$feature.RegistryKey
|
||||
}
|
||||
|
||||
throw "Unable to find registry undo file for backup: $undoKeyDescription ($regFilePath)"
|
||||
}
|
||||
|
||||
foreach ($operation in @(Get-RegFileOperations -regFilePath $regFilePath)) {
|
||||
if (-not $operation.KeyPath) { continue }
|
||||
Add-RegistryPlanOperation -PlanMap $planMap -Operation $operation
|
||||
}
|
||||
}
|
||||
|
||||
return @(
|
||||
foreach ($entry in $planMap.Values) {
|
||||
[PSCustomObject]@{
|
||||
Path = $entry.Path
|
||||
IncludeSubKeys = [bool]$entry.IncludeSubKeys
|
||||
CaptureAllValues = [bool]$entry.CaptureAllValues
|
||||
ValueNames = @($entry.ValueNames)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function Add-RegistryPlanOperation {
|
||||
param(
|
||||
[hashtable]$PlanMap,
|
||||
[PSCustomObject]$Operation
|
||||
)
|
||||
|
||||
$mapKey = $Operation.KeyPath.ToLowerInvariant()
|
||||
if (-not $PlanMap.ContainsKey($mapKey)) {
|
||||
$PlanMap[$mapKey] = [PSCustomObject]@{
|
||||
Path = $Operation.KeyPath
|
||||
IncludeSubKeys = $false
|
||||
CaptureAllValues = $false
|
||||
ValueNames = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
}
|
||||
}
|
||||
|
||||
$plan = $PlanMap[$mapKey]
|
||||
switch ($Operation.OperationType) {
|
||||
'DeleteKey' {
|
||||
$plan.IncludeSubKeys = $true
|
||||
$plan.CaptureAllValues = $true
|
||||
}
|
||||
'SetValue' {
|
||||
if (-not $plan.CaptureAllValues) {
|
||||
$null = $plan.ValueNames.Add([string]$Operation.ValueName)
|
||||
}
|
||||
}
|
||||
'DeleteValue' {
|
||||
if (-not $plan.CaptureAllValues) {
|
||||
$null = $plan.ValueNames.Add([string]$Operation.ValueName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Resolve-RegistryBackupUndoFilePath {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Feature
|
||||
)
|
||||
|
||||
$undoRegistryKey = [string]$Feature.RegistryUndoKey
|
||||
if (-not [string]::IsNullOrWhiteSpace($undoRegistryKey)) {
|
||||
$resolvedUndoPath = Resolve-UndoRegFilePath -FileName $undoRegistryKey
|
||||
return Join-Path $script:RegfilesPath $resolvedUndoPath
|
||||
}
|
||||
|
||||
$resolvedRegistryKey = [string]$Feature.RegistryKey
|
||||
if ([string]::IsNullOrWhiteSpace($resolvedRegistryKey)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if ([System.IO.Path]::IsPathRooted($resolvedRegistryKey)) {
|
||||
return $resolvedRegistryKey
|
||||
}
|
||||
|
||||
return Join-Path $script:RegfilesPath $resolvedRegistryKey
|
||||
}
|
||||
|
||||
function Get-RegistrySnapshotsForBackup {
|
||||
param(
|
||||
[object[]]$CapturePlans = @()
|
||||
)
|
||||
|
||||
if ($CapturePlans.Count -eq 0) {
|
||||
return @()
|
||||
}
|
||||
|
||||
$snapshotScript = {
|
||||
param($plans)
|
||||
|
||||
$snapshots = @()
|
||||
foreach ($plan in $plans) {
|
||||
$snapshots += Get-RegistryKeySnapshot -KeyPath $plan.Path -CaptureAllValues:$plan.CaptureAllValues -ValueNames @($plan.ValueNames) -IncludeSubKeys:$plan.IncludeSubKeys
|
||||
}
|
||||
|
||||
return @($snapshots)
|
||||
}
|
||||
|
||||
if ($script:Params.ContainsKey('Sysprep') -or $script:Params.ContainsKey('User')) {
|
||||
return Invoke-WithLoadedBackupHive -ScriptBlock $snapshotScript -ArgumentObject @($CapturePlans)
|
||||
}
|
||||
|
||||
return & $snapshotScript $CapturePlans
|
||||
}
|
||||
|
||||
function Invoke-WithLoadedBackupHive {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[scriptblock]$ScriptBlock,
|
||||
$ArgumentObject = $null
|
||||
)
|
||||
|
||||
$targetUserName = if ($script:Params.ContainsKey('Sysprep')) {
|
||||
'Default'
|
||||
}
|
||||
else {
|
||||
$script:Params.Item('User')
|
||||
}
|
||||
|
||||
return Invoke-WithTargetUserHive -TargetUserName $targetUserName -ScriptBlock $ScriptBlock -ArgumentObject $ArgumentObject
|
||||
}
|
||||
|
||||
function Get-RegistryKeySnapshot {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$KeyPath,
|
||||
[bool]$CaptureAllValues = $false,
|
||||
[string[]]$ValueNames = @(),
|
||||
[bool]$IncludeSubKeys = $false
|
||||
)
|
||||
|
||||
$registryParts = Split-RegistryPath -path $KeyPath
|
||||
if (-not $registryParts) {
|
||||
throw "Unsupported registry path in backup: $KeyPath"
|
||||
}
|
||||
|
||||
$rootKey = Get-RegistryRootKey -hiveName $registryParts.Hive
|
||||
if (-not $rootKey) {
|
||||
throw "Unsupported registry hive in backup: $($registryParts.Hive)"
|
||||
}
|
||||
|
||||
$subKeyPath = $registryParts.SubKey
|
||||
$key = $rootKey.OpenSubKey($subKeyPath, $false)
|
||||
if ($null -eq $key) {
|
||||
return @{
|
||||
Path = $KeyPath
|
||||
Exists = $false
|
||||
Values = @()
|
||||
SubKeys = @()
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return (Convert-RegistryKeyToSnapshot -RegistryKey $key -FullPath $KeyPath -CaptureAllValues:$CaptureAllValues -ValueNames $ValueNames -IncludeSubKeys:$IncludeSubKeys)
|
||||
}
|
||||
finally {
|
||||
$key.Close()
|
||||
}
|
||||
}
|
||||
|
||||
function Convert-RegistryKeyToSnapshot {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Microsoft.Win32.RegistryKey]$RegistryKey,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FullPath,
|
||||
[bool]$CaptureAllValues = $false,
|
||||
[string[]]$ValueNames = @(),
|
||||
[bool]$IncludeSubKeys = $false
|
||||
)
|
||||
|
||||
$values = @()
|
||||
if ($CaptureAllValues) {
|
||||
foreach ($valueName in @($RegistryKey.GetValueNames())) {
|
||||
$values += @(Convert-RegistryValueToSnapshot -RegistryKey $RegistryKey -ValueName $valueName)
|
||||
}
|
||||
}
|
||||
else {
|
||||
foreach ($valueName in @($ValueNames | Sort-Object -Unique)) {
|
||||
$exists = ($RegistryKey.GetValueNames() -contains $valueName)
|
||||
if ($exists) {
|
||||
$values += @(Convert-RegistryValueToSnapshot -RegistryKey $RegistryKey -ValueName $valueName)
|
||||
}
|
||||
else {
|
||||
$values += @{
|
||||
Name = $valueName
|
||||
Exists = $false
|
||||
Kind = $null
|
||||
Data = $null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$subKeys = @()
|
||||
if ($IncludeSubKeys) {
|
||||
foreach ($subKeyName in @($RegistryKey.GetSubKeyNames())) {
|
||||
$childKey = $RegistryKey.OpenSubKey($subKeyName, $false)
|
||||
if ($null -eq $childKey) { continue }
|
||||
|
||||
try {
|
||||
$childPath = if ([string]::IsNullOrWhiteSpace($FullPath)) { $subKeyName } else { "$FullPath\$subKeyName" }
|
||||
$subKeys += @(Convert-RegistryKeyToSnapshot -RegistryKey $childKey -FullPath $childPath -CaptureAllValues:$true -IncludeSubKeys:$true)
|
||||
}
|
||||
finally {
|
||||
$childKey.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return @{
|
||||
Path = $FullPath
|
||||
Exists = $true
|
||||
Values = $values
|
||||
SubKeys = $subKeys
|
||||
}
|
||||
}
|
||||
|
||||
function Convert-RegistryValueToSnapshot {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Microsoft.Win32.RegistryKey]$RegistryKey,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyString()]
|
||||
[string]$ValueName
|
||||
)
|
||||
|
||||
$valueKind = $RegistryKey.GetValueKind($ValueName)
|
||||
$value = $RegistryKey.GetValue($ValueName, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
try {
|
||||
$normalizedValue = switch ($valueKind) {
|
||||
([Microsoft.Win32.RegistryValueKind]::Binary) { @($value | ForEach-Object { [int]$_ }) }
|
||||
([Microsoft.Win32.RegistryValueKind]::MultiString) { @($value) }
|
||||
([Microsoft.Win32.RegistryValueKind]::DWord) { [BitConverter]::ToUInt32([BitConverter]::GetBytes([int32]$value), 0) }
|
||||
([Microsoft.Win32.RegistryValueKind]::QWord) { [BitConverter]::ToUInt64([BitConverter]::GetBytes([int64]$value), 0) }
|
||||
default { if ($null -ne $value) { [string]$value } else { $null } }
|
||||
}
|
||||
}
|
||||
catch {
|
||||
$valueType = if ($null -ne $value) { $value.GetType().FullName } else { '<null>' }
|
||||
$valueForLog = if ($null -eq $value) { '<null>' } elseif ($value -is [array]) { ($value -join ',') } else { [string]$value }
|
||||
throw "Failed to normalize registry value for backup. Key='$($RegistryKey.Name)' Name='$ValueName' Kind='$valueKind' RawType='$valueType' RawValue='$valueForLog'. InnerError: $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
return @{
|
||||
Name = $ValueName
|
||||
Exists = $true
|
||||
Kind = $valueKind.ToString()
|
||||
Data = $normalizedValue
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RegistryBackupTargetDescription {
|
||||
if ($script:Params.ContainsKey('Sysprep')) {
|
||||
return 'DefaultUserProfile'
|
||||
}
|
||||
|
||||
$resolvedUserName = [string](GetUserName)
|
||||
|
||||
if ($script:Params.ContainsKey('User')) {
|
||||
return "User:$resolvedUserName"
|
||||
}
|
||||
|
||||
return "CurrentUser:$resolvedUserName"
|
||||
}
|
||||
110
Scripts/Features/BackupRegistryState.ps1
Normal file
110
Scripts/Features/BackupRegistryState.ps1
Normal file
@@ -0,0 +1,110 @@
|
||||
function New-RegistrySettingsBackup {
|
||||
param(
|
||||
[string[]]$ActionableKeys,
|
||||
[object[]]$ExtraFeatures = @()
|
||||
)
|
||||
|
||||
$ActionableKeys = @($ActionableKeys)
|
||||
$selectedFeatures = @(Get-SelectedFeatures -ActionableKeys $ActionableKeys)
|
||||
$undoFeatures = @($ExtraFeatures | Where-Object { $_ -ne $null })
|
||||
$allFeatures = @($selectedFeatures) + @($undoFeatures)
|
||||
if (@($allFeatures | Where-Object { -not [string]::IsNullOrWhiteSpace([string]$_.RegistryKey) }).Count -eq 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$timestamp = Get-Date
|
||||
$backupDirectory = $script:RegistryBackupsPath
|
||||
if (-not (Test-Path $backupDirectory)) {
|
||||
New-Item -ItemType Directory -Path $backupDirectory -Force | Out-Null
|
||||
}
|
||||
|
||||
$backupFileName = 'Win11Debloat-RegistryBackup-{0}.json' -f $timestamp.ToString('yyyyMMdd_HHmmss')
|
||||
$backupFilePath = Join-Path $backupDirectory $backupFileName
|
||||
|
||||
$backupConfig = Get-RegistryBackupPayload -SelectedFeatures $selectedFeatures -UndoFeatures $undoFeatures -CreatedAt $timestamp
|
||||
if (-not (SaveToFile -Config $backupConfig -FilePath $backupFilePath -MaxDepth 25)) {
|
||||
throw "Failed to save registry backup to '$backupFilePath'"
|
||||
}
|
||||
|
||||
Write-Host "Backup successfully created: $backupFilePath"
|
||||
Write-Host ""
|
||||
|
||||
return $backupFilePath
|
||||
}
|
||||
|
||||
function Get-SelectedFeatures {
|
||||
param(
|
||||
[string[]]$ActionableKeys
|
||||
)
|
||||
|
||||
$selectedFeatures = New-Object System.Collections.Generic.List[object]
|
||||
$selectedFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
|
||||
foreach ($paramKey in $ActionableKeys) {
|
||||
if (-not $script:Features.ContainsKey($paramKey)) { continue }
|
||||
|
||||
$feature = $script:Features[$paramKey]
|
||||
if (-not $feature) { continue }
|
||||
|
||||
$featureId = Get-FeatureId -Feature $feature
|
||||
|
||||
if ($selectedFeatureIds.Add($featureId)) {
|
||||
$selectedFeatures.Add($feature)
|
||||
}
|
||||
}
|
||||
|
||||
return @($selectedFeatures.ToArray())
|
||||
}
|
||||
|
||||
function Get-RegistryBackupPayload {
|
||||
param(
|
||||
[object[]]$SelectedFeatures = @(),
|
||||
[object[]]$UndoFeatures = @(),
|
||||
[Parameter(Mandatory)]
|
||||
[datetime]$CreatedAt
|
||||
)
|
||||
|
||||
$selectedFeatureIds = New-Object System.Collections.Generic.List[string]
|
||||
$seenSelectedFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($feature in $SelectedFeatures) {
|
||||
$featureId = Get-FeatureId -Feature $feature
|
||||
|
||||
if ($seenSelectedFeatureIds.Add($featureId)) {
|
||||
$selectedFeatureIds.Add($featureId)
|
||||
}
|
||||
}
|
||||
|
||||
$selectedUndoFeatureIds = New-Object System.Collections.Generic.List[string]
|
||||
$seenUndoFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($feature in $UndoFeatures) {
|
||||
$featureId = Get-FeatureId -Feature $feature
|
||||
|
||||
if ($seenUndoFeatureIds.Add($featureId)) {
|
||||
$selectedUndoFeatureIds.Add($featureId)
|
||||
}
|
||||
}
|
||||
|
||||
$selectedRegistryFeatures = @(Get-RegistryBackedFeatures -Features $SelectedFeatures)
|
||||
$undoRegistryFeatures = @($UndoFeatures | Where-Object {
|
||||
-not [string]::IsNullOrWhiteSpace([string]$_.RegistryUndoKey) -or -not [string]::IsNullOrWhiteSpace([string]$_.RegistryKey)
|
||||
})
|
||||
$capturePlans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures $selectedRegistryFeatures -UndoRegistryFeatures $undoRegistryFeatures)
|
||||
$registryKeys = @(Get-RegistrySnapshotsForBackup -CapturePlans $capturePlans)
|
||||
|
||||
$backupPayload = @{
|
||||
Version = '1.0'
|
||||
BackupType = 'RegistryState'
|
||||
CreatedAt = $CreatedAt.ToString('o')
|
||||
CreatedBy = 'Win11Debloat'
|
||||
Target = (Get-RegistryBackupTargetDescription)
|
||||
ComputerName = $env:COMPUTERNAME
|
||||
SelectedFeatures = @($selectedFeatureIds)
|
||||
RegistryKeys = @($registryKeys)
|
||||
}
|
||||
|
||||
if ($selectedUndoFeatureIds.Count -gt 0) {
|
||||
$backupPayload['SelectedUndoFeatures'] = @($selectedUndoFeatureIds)
|
||||
}
|
||||
|
||||
return $backupPayload
|
||||
}
|
||||
@@ -6,7 +6,7 @@ function CreateSystemRestorePoint {
|
||||
# In GUI mode, skip the prompt and just try to enable it
|
||||
if ($script:GuiWindow -or $Silent -or $( Read-Host -Prompt "System restore is disabled, would you like to enable it and create a restore point? (y/n)") -eq 'y') {
|
||||
try {
|
||||
$enableResult = Invoke-NonBlocking -TimeoutSeconds 20 -ScriptBlock {
|
||||
$enableResult = Invoke-NonBlocking -TimeoutSeconds 90 -ScriptBlock {
|
||||
try {
|
||||
Enable-ComputerRestore -Drive "$env:SystemDrive"
|
||||
return $null
|
||||
@@ -33,7 +33,7 @@ function CreateSystemRestorePoint {
|
||||
|
||||
if (-not $failed) {
|
||||
try {
|
||||
$result = Invoke-NonBlocking -TimeoutSeconds 20 -ScriptBlock {
|
||||
$result = Invoke-NonBlocking -TimeoutSeconds 90 -ScriptBlock {
|
||||
try {
|
||||
$recentRestorePoints = Get-ComputerRestorePoint | Where-Object { (Get-Date) - [System.Management.ManagementDateTimeConverter]::ToDateTime($_.CreationTime) -le (New-TimeSpan -Hours 24) }
|
||||
}
|
||||
@@ -92,4 +92,4 @@ function CreateSystemRestorePoint {
|
||||
|
||||
Write-Host "Warning: Continuing without restore point" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
function DisableStoreSearchSuggestionsForAllUsers {
|
||||
# Get path to Store app database for all users
|
||||
$userPathString = GetUserDirectory -userName "*" -fileName "AppData\Local\Packages"
|
||||
$usersStoreDbPaths = get-childitem -path $userPathString
|
||||
$usersStoreDbPaths = Get-ChildItem -Path $userPathString -ErrorAction SilentlyContinue
|
||||
|
||||
# Go through all users and disable start search suggestions
|
||||
ForEach ($storeDbPath in $usersStoreDbPaths) {
|
||||
@@ -49,4 +49,137 @@ function DisableStoreSearchSuggestions {
|
||||
Set-Acl -Path $StoreAppsDatabase -AclObject $Acl | Out-Null
|
||||
|
||||
Write-Host "Disabled Microsoft Store search suggestions for user $userName"
|
||||
}
|
||||
|
||||
function EnableStoreSearchSuggestionsForAllUsers {
|
||||
# Get path to Store app database for all users
|
||||
$userPathString = GetUserDirectory -userName "*" -fileName "AppData\Local\Packages"
|
||||
$usersStoreDbPaths = Get-ChildItem -Path $userPathString -ErrorAction SilentlyContinue
|
||||
|
||||
# Go through all users and re-enable start search suggestions
|
||||
ForEach ($storeDbPath in $usersStoreDbPaths) {
|
||||
EnableStoreSearchSuggestions ($storeDbPath.FullName + "\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db")
|
||||
}
|
||||
|
||||
# Also re-enable for the default user profile
|
||||
$defaultStoreDbPath = GetUserDirectory -userName "Default" -fileName "AppData\Local\Packages\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db" -exitIfPathNotFound $false
|
||||
EnableStoreSearchSuggestions $defaultStoreDbPath
|
||||
}
|
||||
|
||||
function EnableStoreSearchSuggestions {
|
||||
param (
|
||||
$StoreAppsDatabase = "$env:LocalAppData\Packages\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db"
|
||||
)
|
||||
|
||||
# Change path to correct user if a user was specified
|
||||
if ($script:Params.ContainsKey("User")) {
|
||||
$StoreAppsDatabase = GetUserDirectory -userName "$(GetUserName)" -fileName "AppData\Local\Packages\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db" -exitIfPathNotFound $false
|
||||
}
|
||||
|
||||
$userName = [regex]::Match($StoreAppsDatabase, '(?:Users\\)([^\\]+)(?:\\AppData)').Groups[1].Value
|
||||
if (-not $userName) { $userName = '<unknown>' }
|
||||
|
||||
if (-not (Test-Path -Path $StoreAppsDatabase)) {
|
||||
Write-Host "Store app database not found for user $userName, nothing to undo"
|
||||
return
|
||||
}
|
||||
|
||||
# Ensure we can modify/delete the file even if restrictive ACLs were set.
|
||||
$global:LASTEXITCODE = 0
|
||||
takeown /F "$StoreAppsDatabase" /A | Out-Null
|
||||
icacls "$StoreAppsDatabase" /grant *S-1-5-32-544:F /C | Out-Null
|
||||
|
||||
$everyoneSid = [System.Security.Principal.SecurityIdentifier]::new('S-1-1-0') # 'EVERYONE' group
|
||||
|
||||
try {
|
||||
$acl = Get-Acl -Path $StoreAppsDatabase
|
||||
$denyRules = @(
|
||||
$acl.Access | Where-Object {
|
||||
$_.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
||||
(($_.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::FullControl) -ne 0) -and
|
||||
(try { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) -eq $everyoneSid } catch { $false })
|
||||
}
|
||||
)
|
||||
|
||||
foreach ($denyRule in $denyRules) {
|
||||
$null = $acl.RemoveAccessRuleSpecific($denyRule)
|
||||
}
|
||||
|
||||
Set-Acl -Path $StoreAppsDatabase -AclObject $acl | Out-Null
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Failed to normalize ACL for store database '$StoreAppsDatabase': $($_.Exception.Message)"
|
||||
}
|
||||
|
||||
try {
|
||||
Remove-Item -Path $StoreAppsDatabase -Force -ErrorAction Stop
|
||||
Write-Host "Re-enabled Microsoft Store search suggestions for user $userName"
|
||||
}
|
||||
catch {
|
||||
throw "Failed to remove '$StoreAppsDatabase' while undoing Microsoft Store search suggestions for user $userName. $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
function Test-StoreSearchSuggestionsDisabled {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$StoreAppsDatabase
|
||||
)
|
||||
|
||||
if (-not (Test-Path -Path $StoreAppsDatabase)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
try {
|
||||
$acl = Get-Acl -Path $StoreAppsDatabase
|
||||
}
|
||||
catch {
|
||||
return $false
|
||||
}
|
||||
|
||||
$everyoneSid = [System.Security.Principal.SecurityIdentifier]::new('S-1-1-0')
|
||||
|
||||
foreach ($accessRule in @($acl.Access)) {
|
||||
$isDenyFullControl = $accessRule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Deny -and
|
||||
(($accessRule.FileSystemRights -band [System.Security.AccessControl.FileSystemRights]::FullControl) -ne 0)
|
||||
if (-not $isDenyFullControl) { continue }
|
||||
|
||||
$isEveryone = $false
|
||||
try {
|
||||
$isEveryone = $accessRule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]) -eq $everyoneSid
|
||||
} catch { }
|
||||
|
||||
if ($isEveryone) {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
|
||||
return $false
|
||||
}
|
||||
|
||||
function Test-StoreSearchSuggestionsDisabledForAllUsers {
|
||||
$paths = @()
|
||||
|
||||
$userPathString = GetUserDirectory -userName "*" -fileName "AppData\Local\Packages"
|
||||
$usersStoreDbPaths = Get-ChildItem -Path $userPathString -ErrorAction SilentlyContinue
|
||||
foreach ($storeDbPath in $usersStoreDbPaths) {
|
||||
$paths += ($storeDbPath.FullName + "\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db")
|
||||
}
|
||||
|
||||
$defaultStoreDbPath = GetUserDirectory -userName "Default" -fileName "AppData\Local\Packages\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db" -exitIfPathNotFound $false
|
||||
if ($defaultStoreDbPath) {
|
||||
$paths += $defaultStoreDbPath
|
||||
}
|
||||
|
||||
if ($paths.Count -eq 0) {
|
||||
return $false
|
||||
}
|
||||
|
||||
foreach ($path in $paths) {
|
||||
if (-not (Test-StoreSearchSuggestionsDisabled -StoreAppsDatabase $path)) {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
# Enables a Windows optional feature and pipes its output to the console
|
||||
function EnableWindowsFeature {
|
||||
param (
|
||||
[string]$FeatureName
|
||||
)
|
||||
|
||||
$result = Invoke-NonBlocking -ScriptBlock {
|
||||
param($name)
|
||||
Enable-WindowsOptionalFeature -Online -FeatureName $name -All -NoRestart
|
||||
} -ArgumentList $FeatureName
|
||||
|
||||
$dismResult = @($result) | Where-Object { $_ -is [Microsoft.Dism.Commands.ImageObject] }
|
||||
if ($dismResult) {
|
||||
Write-Host ($dismResult | Out-String).Trim()
|
||||
}
|
||||
}
|
||||
@@ -6,35 +6,13 @@ function ExecuteParameter {
|
||||
[string]$paramKey
|
||||
)
|
||||
|
||||
# Check if this feature exists in Features.json
|
||||
# Check if this feature has metadata in Features.json
|
||||
$feature = $null
|
||||
if ($script:Features.ContainsKey($paramKey)) {
|
||||
$feature = $script:Features[$paramKey]
|
||||
}
|
||||
|
||||
# Check if undo is requested and if this feature supports undo
|
||||
$undoChanges = $script:Params.ContainsKey('Undo')
|
||||
|
||||
if ($undoChanges) {
|
||||
$undoFeature = GetUndoFeatureForParam -paramKey $paramKey
|
||||
|
||||
if ($null -eq $undoFeature) {
|
||||
# This parameter doesn't support undo, so skip it
|
||||
return
|
||||
}
|
||||
|
||||
$undoRegFile = $undoFeature.RegistryUndoKey
|
||||
$undoFolderPath = Join-Path $script:RegfilesPath (Join-Path 'Undo' $undoRegFile)
|
||||
|
||||
if (Test-Path $undoFolderPath) {
|
||||
$undoRegFile = Join-Path 'Undo' $undoRegFile
|
||||
}
|
||||
|
||||
ImportRegistryFile "> $($undoFeature.UndoText)" $undoRegFile
|
||||
return
|
||||
}
|
||||
|
||||
# If feature has RegistryKey and ApplyText, dynamically import the registry file for this feature
|
||||
# If feature has RegistryKey and ApplyText, use dynamic ImportRegistryFile
|
||||
if ($feature -and $feature.RegistryKey -and $feature.ApplyText) {
|
||||
ImportRegistryFile "> $($feature.ApplyText)" $feature.RegistryKey
|
||||
|
||||
@@ -42,15 +20,11 @@ function ExecuteParameter {
|
||||
switch ($paramKey) {
|
||||
'DisableBing' {
|
||||
# Also remove the app package for Bing search
|
||||
RemoveApps 'Microsoft.BingSearch'
|
||||
RemoveApps @('Microsoft.BingSearch')
|
||||
}
|
||||
'DisableCopilot' {
|
||||
# Also remove the app package for Copilot
|
||||
RemoveApps 'Microsoft.Copilot'
|
||||
}
|
||||
'DisableWidgets' {
|
||||
# Also remove the app packages for Widgets
|
||||
RemoveApps 'Microsoft.StartExperiencesApp','MicrosoftWindows.Client.WebExperience','Microsoft.WidgetsPlatformRuntime'
|
||||
RemoveApps @('Microsoft.Copilot')
|
||||
}
|
||||
}
|
||||
return
|
||||
@@ -59,7 +33,7 @@ function ExecuteParameter {
|
||||
# Handle features without RegistryKey or with special logic
|
||||
switch ($paramKey) {
|
||||
'RemoveApps' {
|
||||
Write-Host "> Removing selected apps for $(GetFriendlyTargetUserName)..."
|
||||
Write-Host "> $($feature.ApplyText) for $(GetFriendlyTargetUserName)..."
|
||||
$appsList = GenerateAppsList
|
||||
|
||||
if ($appsList.Count -eq 0) {
|
||||
@@ -72,7 +46,7 @@ function ExecuteParameter {
|
||||
RemoveApps $appsList
|
||||
}
|
||||
'RemoveAppsCustom' {
|
||||
Write-Host "> Removing selected apps..."
|
||||
Write-Host "> $($feature.ApplyText)..."
|
||||
$appsList = LoadAppsFromFile $script:CustomAppsListFilePath
|
||||
|
||||
if ($appsList.Count -eq 0) {
|
||||
@@ -84,51 +58,46 @@ function ExecuteParameter {
|
||||
Write-Host "$($appsList.Count) apps selected for removal"
|
||||
RemoveApps $appsList
|
||||
}
|
||||
'RemoveCommApps' {
|
||||
$appsList = 'Microsoft.windowscommunicationsapps', 'Microsoft.People'
|
||||
Write-Host "> Removing Mail, Calendar and People apps..."
|
||||
RemoveApps $appsList
|
||||
return
|
||||
}
|
||||
'RemoveW11Outlook' {
|
||||
$appsList = 'Microsoft.OutlookForWindows'
|
||||
Write-Host "> Removing new Outlook for Windows app..."
|
||||
RemoveApps $appsList
|
||||
return
|
||||
}
|
||||
'RemoveGamingApps' {
|
||||
$appsList = 'Microsoft.GamingApp', 'Microsoft.XboxGameOverlay', 'Microsoft.XboxGamingOverlay'
|
||||
Write-Host "> Removing gaming related apps..."
|
||||
$appsList = @('Microsoft.GamingApp', 'Microsoft.XboxGameOverlay', 'Microsoft.XboxGamingOverlay')
|
||||
Write-Host "> $($feature.ApplyText)..."
|
||||
RemoveApps $appsList
|
||||
return
|
||||
}
|
||||
'RemoveHPApps' {
|
||||
$appsList = 'AD2F1837.HPAIExperienceCenter', 'AD2F1837.HPJumpStarts', 'AD2F1837.HPPCHardwareDiagnosticsWindows', 'AD2F1837.HPPowerManager', 'AD2F1837.HPPrivacySettings', 'AD2F1837.HPSupportAssistant', 'AD2F1837.HPSureShieldAI', 'AD2F1837.HPSystemInformation', 'AD2F1837.HPQuickDrop', 'AD2F1837.HPWorkWell', 'AD2F1837.myHP', 'AD2F1837.HPDesktopSupportUtilities', 'AD2F1837.HPQuickTouch', 'AD2F1837.HPEasyClean', 'AD2F1837.HPConnectedMusic', 'AD2F1837.HPFileViewer', 'AD2F1837.HPRegistration', 'AD2F1837.HPWelcome', 'AD2F1837.HPConnectedPhotopoweredbySnapfish', 'AD2F1837.HPPrinterControl'
|
||||
Write-Host "> Removing HP apps..."
|
||||
$appsList = @('AD2F1837.HPAIExperienceCenter', 'AD2F1837.HPJumpStarts', 'AD2F1837.HPPCHardwareDiagnosticsWindows', 'AD2F1837.HPPowerManager', 'AD2F1837.HPPrivacySettings', 'AD2F1837.HPSupportAssistant', 'AD2F1837.HPSureShieldAI', 'AD2F1837.HPSystemInformation', 'AD2F1837.HPQuickDrop', 'AD2F1837.HPWorkWell', 'AD2F1837.myHP', 'AD2F1837.HPDesktopSupportUtilities', 'AD2F1837.HPQuickTouch', 'AD2F1837.HPEasyClean', 'AD2F1837.HPConnectedMusic', 'AD2F1837.HPFileViewer', 'AD2F1837.HPRegistration', 'AD2F1837.HPWelcome', 'AD2F1837.HPConnectedPhotopoweredbySnapfish', 'AD2F1837.HPPrinterControl')
|
||||
Write-Host "> $($feature.ApplyText)..."
|
||||
RemoveApps $appsList
|
||||
return
|
||||
}
|
||||
"EnableWindowsSandbox" {
|
||||
Write-Host "> Enabling Windows Sandbox..."
|
||||
'DisableWidgets' {
|
||||
Write-Host "> $($feature.ApplyText)..."
|
||||
# Stop widgets related processes before removing the app packages to prevent potential issues
|
||||
Get-Process *Widget* -ErrorAction SilentlyContinue | Stop-Process
|
||||
|
||||
RemoveApps @('Microsoft.StartExperiencesApp','MicrosoftWindows.Client.WebExperience','Microsoft.WidgetsPlatformRuntime')
|
||||
}
|
||||
'EnableWindowsSandbox' {
|
||||
Write-Host "> $($feature.ApplyText)..."
|
||||
EnableWindowsFeature "Containers-DisposableClientVM"
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
"EnableWindowsSubsystemForLinux" {
|
||||
Write-Host "> Enabling Windows Subsystem for Linux..."
|
||||
'EnableWindowsSubsystemForLinux' {
|
||||
Write-Host "> $($feature.ApplyText)..."
|
||||
EnableWindowsFeature "VirtualMachinePlatform"
|
||||
EnableWindowsFeature "Microsoft-Windows-Subsystem-Linux"
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
'ClearStart' {
|
||||
Write-Host "> Removing all pinned apps from the start menu for user $(GetUserName)..."
|
||||
Write-Host "> $($feature.ApplyText) for user $(GetUserName)..."
|
||||
ReplaceStartMenu
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
'ReplaceStart' {
|
||||
Write-Host "> Replacing the start menu for user $(GetUserName)..."
|
||||
Write-Host "> $($feature.ApplyText) for user $(GetUserName)..."
|
||||
ReplaceStartMenu $script:Params.Item("ReplaceStart")
|
||||
Write-Host ""
|
||||
return
|
||||
@@ -159,59 +128,83 @@ function ExecuteParameter {
|
||||
|
||||
|
||||
# Executes all selected parameters/features
|
||||
function ExecuteAllChanges {
|
||||
function ExecuteAllChanges {
|
||||
# When running as SYSTEM, require -User or -Sysprep to prevent applying
|
||||
# changes to the SYSTEM profile instead of a real user.
|
||||
$isSystem = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -eq 'S-1-5-18')
|
||||
if ($isSystem -and -not $script:Params.ContainsKey("User") -and -not $script:Params.ContainsKey("Sysprep")) {
|
||||
throw "Win11Debloat is running as the SYSTEM account. Use the '-User' or '-Sysprep' parameter to target a specific user."
|
||||
}
|
||||
|
||||
$script:RegistryImportFailures = 0
|
||||
|
||||
# Build list of actionable parameters (skip control params and data-only params)
|
||||
$undoChanges = $script:Params.ContainsKey('Undo')
|
||||
$actionableKeys = @()
|
||||
$paramsToRemove = @()
|
||||
foreach ($paramKey in $script:Params.Keys) {
|
||||
if ($script:ControlParams -contains $paramKey) { continue }
|
||||
if ($paramKey -eq 'Apps') { continue }
|
||||
if ($paramKey -eq 'CreateRestorePoint') { continue }
|
||||
|
||||
if ($undoChanges) {
|
||||
$undoFeature = GetUndoFeatureForParam -paramKey $paramKey
|
||||
if (-not $undoFeature) {
|
||||
$paramsToRemove += $paramKey
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
$actionableKeys += $paramKey
|
||||
}
|
||||
|
||||
if ($undoChanges -and $paramsToRemove.Count -gt 0) {
|
||||
foreach ($paramKey in ($paramsToRemove | Sort-Object -Unique)) {
|
||||
if ($script:Params.ContainsKey($paramKey)) {
|
||||
$null = $script:Params.Remove($paramKey)
|
||||
}
|
||||
$hasRegistryBackedFeature = $false
|
||||
foreach ($paramKey in $actionableKeys) {
|
||||
if (-not $script:Features.ContainsKey($paramKey)) { continue }
|
||||
|
||||
$feature = $script:Features[$paramKey]
|
||||
if ($feature -and -not [string]::IsNullOrWhiteSpace([string]$feature.RegistryKey)) {
|
||||
$hasRegistryBackedFeature = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($undoChanges -and $actionableKeys.Count -eq 0) {
|
||||
throw "Undo was requested but none of the selected parameters support undo. No changes were reverted."
|
||||
# Undo operations that write registry values also require a backup
|
||||
if (-not $hasRegistryBackedFeature) {
|
||||
foreach ($featureId in $script:UndoParams.Keys) {
|
||||
$f = if ($script:Features.ContainsKey($featureId)) { $script:Features[$featureId] } else { $null }
|
||||
if ($f -and $f.RegistryUndoKey) { $hasRegistryBackedFeature = $true; break }
|
||||
}
|
||||
}
|
||||
|
||||
$totalSteps = $actionableKeys.Count
|
||||
$totalSteps = $actionableKeys.Count + $script:UndoParams.Count
|
||||
if ($hasRegistryBackedFeature) { $totalSteps++ }
|
||||
if ($script:Params.ContainsKey("CreateRestorePoint")) { $totalSteps++ }
|
||||
$currentStep = 0
|
||||
|
||||
if ($hasRegistryBackedFeature) {
|
||||
$currentStep++
|
||||
if ($script:ApplyProgressCallback) {
|
||||
& $script:ApplyProgressCallback $currentStep $totalSteps "Creating registry backup..."
|
||||
}
|
||||
|
||||
Write-Host "> Creating registry backup..."
|
||||
try {
|
||||
$undoSyntheticFeatures = @($script:UndoParams.Keys | ForEach-Object {
|
||||
$f = if ($script:Features.ContainsKey($_)) { $script:Features[$_] } else { $null }
|
||||
if ($f -and $f.RegistryUndoKey) {
|
||||
[PSCustomObject]@{ FeatureId = $_; RegistryKey = (Resolve-UndoRegFilePath $f.RegistryUndoKey) }
|
||||
}
|
||||
} | Where-Object { $_ })
|
||||
New-RegistrySettingsBackup -ActionableKeys $actionableKeys -ExtraFeatures $undoSyntheticFeatures | Out-Null
|
||||
}
|
||||
catch {
|
||||
throw "Registry backup failed before applying changes. $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
# Create restore point if requested (CLI only - GUI handles this separately)
|
||||
if ($script:Params.ContainsKey("CreateRestorePoint")) {
|
||||
$currentStep++
|
||||
if ($script:ApplyProgressCallback) {
|
||||
& $script:ApplyProgressCallback $currentStep $totalSteps "Creating system restore point"
|
||||
& $script:ApplyProgressCallback $currentStep $totalSteps "Creating system restore point, this may take a moment..."
|
||||
}
|
||||
Write-Host "> Attempting to create a system restore point..."
|
||||
Write-Host "> Creating a system restore point..."
|
||||
CreateSystemRestorePoint
|
||||
Write-Host ""
|
||||
}
|
||||
|
||||
# Execute all parameters
|
||||
foreach ($paramKey in $actionableKeys) {
|
||||
if ($script:CancelRequested) {
|
||||
return
|
||||
}
|
||||
if ($script:CancelRequested) { return }
|
||||
|
||||
$currentStep++
|
||||
|
||||
@@ -219,13 +212,12 @@ function ExecuteAllChanges {
|
||||
$stepName = $paramKey
|
||||
if ($script:Features.ContainsKey($paramKey)) {
|
||||
$feature = $script:Features[$paramKey]
|
||||
if ($undoChanges -and $feature.UndoText) {
|
||||
$stepName = $feature.UndoText
|
||||
}
|
||||
elseif ($feature.ApplyText) {
|
||||
if ($feature.ApplyText) {
|
||||
# Prefer explicit ApplyText when provided
|
||||
$stepName = $feature.ApplyText
|
||||
} elseif ($feature.Action) {
|
||||
$stepName = $feature.Action
|
||||
} elseif ($feature.Label) {
|
||||
# Fallback: use label from Features.json
|
||||
$stepName = $feature.Label
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,4 +227,83 @@ function ExecuteAllChanges {
|
||||
|
||||
ExecuteParameter -paramKey $paramKey
|
||||
}
|
||||
|
||||
# Execute all undo operations
|
||||
foreach ($featureId in $script:UndoParams.Keys) {
|
||||
if ($script:CancelRequested) { return }
|
||||
|
||||
$f = if ($script:Features.ContainsKey($featureId)) { $script:Features[$featureId] } else { $null }
|
||||
$undoLabel = if ($f -and $f.UndoLabel) { $f.UndoLabel } else { $featureId }
|
||||
$applyUndoText = if ($f -and $f.ApplyUndoText) { $f.ApplyUndoText } else { $undoLabel }
|
||||
|
||||
$currentStep++
|
||||
if ($script:ApplyProgressCallback) {
|
||||
& $script:ApplyProgressCallback $currentStep $totalSteps $applyUndoText
|
||||
}
|
||||
|
||||
if ($f -and $f.RegistryUndoKey) {
|
||||
ImportRegistryFile "> $applyUndoText" (Resolve-UndoRegFilePath $f.RegistryUndoKey)
|
||||
} else {
|
||||
Invoke-UndoFeatureAction -FeatureId $featureId
|
||||
}
|
||||
}
|
||||
|
||||
if ($script:RegistryImportFailures -gt 0) {
|
||||
Write-Host ""
|
||||
Write-Host "$($script:RegistryImportFailures) registry import change(s) failed. See output above for details." -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
# Resolves the path of an undo reg file relative to $script:RegfilesPath.
|
||||
# Checks the Undo/ subfolder first, then falls back to the root Regfiles/ folder.
|
||||
function Resolve-UndoRegFilePath {
|
||||
param ([string]$FileName)
|
||||
$undoSubPath = Join-Path 'Undo' $FileName
|
||||
if (Test-Path (Join-Path $script:RegfilesPath $undoSubPath)) {
|
||||
return $undoSubPath
|
||||
}
|
||||
return $FileName
|
||||
}
|
||||
|
||||
function Invoke-UndoFeatureAction {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FeatureId
|
||||
)
|
||||
|
||||
$feature = if ($script:Features.ContainsKey($FeatureId)) { $script:Features[$FeatureId] } else { $null }
|
||||
|
||||
switch ($FeatureId) {
|
||||
'DisableStoreSearchSuggestions' {
|
||||
if ($script:Params.ContainsKey('Sysprep')) {
|
||||
Write-Host "> Re-enabling Microsoft Store search suggestions in the start menu for all users..."
|
||||
EnableStoreSearchSuggestionsForAllUsers
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "> Re-enabling Microsoft Store search suggestions for user $(GetUserName)..."
|
||||
EnableStoreSearchSuggestions
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
'EnableWindowsSandbox' {
|
||||
Write-Host "> $($feature.ApplyUndoText)..."
|
||||
DisableWindowsFeature 'Containers-DisposableClientVM'
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
'EnableWindowsSubsystemForLinux' {
|
||||
Write-Host "> $($feature.ApplyUndoText)..."
|
||||
DisableWindowsFeature 'Microsoft-Windows-Subsystem-Linux'
|
||||
DisableWindowsFeature 'VirtualMachinePlatform'
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
default {
|
||||
Write-Host "> No undo action defined for $FeatureId, skipping..." -ForegroundColor Yellow
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
175
Scripts/Features/GetCurrentTweakState.ps1
Normal file
175
Scripts/Features/GetCurrentTweakState.ps1
Normal file
@@ -0,0 +1,175 @@
|
||||
# Tests whether the registry operations in a feature's .reg file currently match the live registry.
|
||||
# Returns $true if ALL operations in the apply reg file match current system state.
|
||||
# Returns $false if the feature has no RegistryKey, the file is missing, or any operation mismatches.
|
||||
function Get-ExpectedRegistryValueKind {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Operation
|
||||
)
|
||||
|
||||
switch ([string]$Operation.ValueType) {
|
||||
'DWord' { return [Microsoft.Win32.RegistryValueKind]::DWord }
|
||||
'QWord' { return [Microsoft.Win32.RegistryValueKind]::QWord }
|
||||
'String' { return [Microsoft.Win32.RegistryValueKind]::String }
|
||||
'Binary' { return [Microsoft.Win32.RegistryValueKind]::Binary }
|
||||
'Hex2' { return [Microsoft.Win32.RegistryValueKind]::ExpandString }
|
||||
'Hex7' { return [Microsoft.Win32.RegistryValueKind]::MultiString }
|
||||
default { return $null }
|
||||
}
|
||||
}
|
||||
|
||||
function Test-FeatureApplied {
|
||||
param (
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FeatureId
|
||||
)
|
||||
|
||||
if (-not $script:Features.ContainsKey($FeatureId)) { return $false }
|
||||
$feature = $script:Features[$FeatureId]
|
||||
|
||||
switch ($FeatureId) {
|
||||
'DisableWidgets' {
|
||||
# Widgets packages cannot be reinstalled automatically, so we treat their
|
||||
# absence as the applied state (checked) and presence as not-yet-applied.
|
||||
$widgetAppIds = @(
|
||||
'Microsoft.StartExperiencesApp',
|
||||
'MicrosoftWindows.Client.WebExperience',
|
||||
'Microsoft.WidgetsPlatformRuntime'
|
||||
)
|
||||
|
||||
foreach ($appId in $widgetAppIds) {
|
||||
if (Get-AppxPackage -Name $appId -AllUsers -ErrorAction SilentlyContinue) {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
'DisableStoreSearchSuggestions' {
|
||||
if ($script:Params.ContainsKey('Sysprep')) {
|
||||
return (Test-StoreSearchSuggestionsDisabledForAllUsers)
|
||||
}
|
||||
|
||||
$storeDbPath = "$env:LocalAppData\Packages\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db"
|
||||
if ($script:Params.ContainsKey('User')) {
|
||||
$storeDbPath = GetUserDirectory -userName "$(GetUserName)" -fileName "AppData\Local\Packages\Microsoft.WindowsStore_8wekyb3d8bbwe\LocalState\store.db" -exitIfPathNotFound $false
|
||||
}
|
||||
|
||||
return (Test-StoreSearchSuggestionsDisabled -StoreAppsDatabase $storeDbPath)
|
||||
}
|
||||
'EnableWindowsSandbox' {
|
||||
return (Test-WindowsOptionalFeatureEnabled -FeatureName 'Containers-DisposableClientVM')
|
||||
}
|
||||
'EnableWindowsSubsystemForLinux' {
|
||||
$wslEnabled = Test-WindowsOptionalFeatureEnabled -FeatureName 'Microsoft-Windows-Subsystem-Linux'
|
||||
$vmpEnabled = Test-WindowsOptionalFeatureEnabled -FeatureName 'VirtualMachinePlatform'
|
||||
return ($wslEnabled -and $vmpEnabled)
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $feature.RegistryKey) { return $false }
|
||||
|
||||
$regFilePath = Join-Path $script:RegfilesPath $feature.RegistryKey
|
||||
if (-not (Test-Path $regFilePath)) { return $false }
|
||||
|
||||
try {
|
||||
$operations = @(Get-RegFileOperations -regFilePath $regFilePath)
|
||||
}
|
||||
catch { return $false }
|
||||
|
||||
if ($operations.Count -eq 0) { return $false }
|
||||
|
||||
foreach ($op in $operations) {
|
||||
$parts = Split-RegistryPath -path $op.KeyPath
|
||||
if (-not $parts) { return $false }
|
||||
|
||||
$rootKey = Get-RegistryRootKey -hiveName $parts.Hive
|
||||
if (-not $rootKey) { return $false }
|
||||
|
||||
$key = $null
|
||||
try {
|
||||
$key = $rootKey.OpenSubKey($parts.SubKey, $false)
|
||||
|
||||
switch ($op.OperationType) {
|
||||
'DeleteKey' {
|
||||
if ($null -ne $key) { return $false }
|
||||
}
|
||||
'DeleteValue' {
|
||||
if ($null -ne $key) {
|
||||
$names = @($key.GetValueNames())
|
||||
if ($names -icontains $op.ValueName) { return $false }
|
||||
}
|
||||
# key missing = value also gone = operation matches
|
||||
}
|
||||
'SetValue' {
|
||||
if ($null -eq $key) { return $false }
|
||||
$names = @($key.GetValueNames())
|
||||
if (-not ($names -icontains $op.ValueName)) { return $false }
|
||||
|
||||
$actualKind = $key.GetValueKind($op.ValueName)
|
||||
$expectedKind = Get-ExpectedRegistryValueKind -Operation $op
|
||||
if ($null -eq $expectedKind -or $actualKind -ne $expectedKind) { return $false }
|
||||
$actualRaw = $key.GetValue($op.ValueName, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
|
||||
$actual = switch ($actualKind) {
|
||||
([Microsoft.Win32.RegistryValueKind]::DWord) {
|
||||
[BitConverter]::ToUInt32([BitConverter]::GetBytes([int32]$actualRaw), 0)
|
||||
}
|
||||
([Microsoft.Win32.RegistryValueKind]::QWord) {
|
||||
[BitConverter]::ToUInt64([BitConverter]::GetBytes([int64]$actualRaw), 0)
|
||||
}
|
||||
([Microsoft.Win32.RegistryValueKind]::Binary) {
|
||||
@($actualRaw | ForEach-Object { [int]$_ })
|
||||
}
|
||||
([Microsoft.Win32.RegistryValueKind]::MultiString) {
|
||||
@($actualRaw)
|
||||
}
|
||||
default {
|
||||
if ($null -ne $actualRaw) { [string]$actualRaw } else { $null }
|
||||
}
|
||||
}
|
||||
|
||||
$expected = $op.ValueData
|
||||
|
||||
$match = if (($actual -is [array]) -and ($expected -is [array])) {
|
||||
(Compare-Object $actual $expected).Count -eq 0
|
||||
} else {
|
||||
$actual -eq $expected
|
||||
}
|
||||
|
||||
if (-not $match) { return $false }
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { return $false }
|
||||
finally {
|
||||
if ($null -ne $key) { $key.Close() }
|
||||
}
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
# Returns the 1-based index of the UiGroup option whose features all match current system state,
|
||||
# or 0 if no option fully matches (meaning the current state is unknown / "No Change").
|
||||
function Get-CurrentGroupActiveIndex {
|
||||
param (
|
||||
[Parameter(Mandatory)]
|
||||
[object]$Group
|
||||
)
|
||||
|
||||
$i = 1
|
||||
foreach ($val in $Group.Values) {
|
||||
$allApplied = $true
|
||||
foreach ($fid in $val.FeatureIds) {
|
||||
if (-not (Test-FeatureApplied -FeatureId $fid)) {
|
||||
$allApplied = $false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ($allApplied) { return $i }
|
||||
$i++
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
@@ -8,33 +8,33 @@ function ImportRegistryFile {
|
||||
Write-Host $message
|
||||
|
||||
$usesOfflineHive = $script:Params.ContainsKey("Sysprep") -or $script:Params.ContainsKey("User")
|
||||
$regFilePath = if ($usesOfflineHive) {
|
||||
"$script:RegfilesPath\Sysprep\$path"
|
||||
}
|
||||
else {
|
||||
"$script:RegfilesPath\$path"
|
||||
}
|
||||
$regFilePath = Get-RegistryFilePathForFeature -RegistryKey $path
|
||||
|
||||
if (-not (Test-Path $regFilePath)) {
|
||||
$errorMessage = "Unable to find registry file: $path ($regFilePath)"
|
||||
$script:RegistryImportFailures++
|
||||
Write-Host "Error: $errorMessage" -ForegroundColor Red
|
||||
Write-Host ""
|
||||
throw $errorMessage
|
||||
}
|
||||
|
||||
# Reset exit code before running reg.exe for reliable success detection
|
||||
$global:LASTEXITCODE = 0
|
||||
$importScript = {
|
||||
param($targetRegFilePath, $hiveContext)
|
||||
|
||||
if ($usesOfflineHive) {
|
||||
# Sysprep targets Default user, User targets the specified user
|
||||
$hiveDatPath = if ($script:Params.ContainsKey("Sysprep")) {
|
||||
GetUserDirectory -userName "Default" -fileName "NTUSER.DAT"
|
||||
} else {
|
||||
GetUserDirectory -userName $script:Params.Item("User") -fileName "NTUSER.DAT"
|
||||
# When the target user's hive is already loaded under their SID, the .reg file's
|
||||
# HKEY_USERS\Default paths won't match. Use the PowerShell registry writer instead,
|
||||
# which remaps Default → SID via Split-RegistryPath.
|
||||
$usePowerShellFallbackOnly = $hiveContext -and [bool]$hiveContext.WasAlreadyLoaded
|
||||
|
||||
if ($usePowerShellFallbackOnly) {
|
||||
Invoke-RegistryOperationsFromRegFile -RegFilePath $targetRegFilePath
|
||||
Write-Host "The operation completed successfully via PowerShell registry writer."
|
||||
Write-Host ""
|
||||
return
|
||||
}
|
||||
|
||||
$regResult = Invoke-NonBlocking -ScriptBlock {
|
||||
param($hivePath, $targetRegFilePath)
|
||||
param($targetRegFilePath)
|
||||
$result = @{
|
||||
Output = @()
|
||||
ExitCode = 0
|
||||
@@ -43,13 +43,6 @@ function ImportRegistryFile {
|
||||
|
||||
try {
|
||||
$global:LASTEXITCODE = 0
|
||||
reg load "HKU\Default" $hivePath | Out-Null
|
||||
$loadExitCode = $LASTEXITCODE
|
||||
|
||||
if ($loadExitCode -ne 0) {
|
||||
throw "Failed to load user hive at '$hivePath' (exit code: $loadExitCode)"
|
||||
}
|
||||
|
||||
$output = reg import $targetRegFilePath 2>&1
|
||||
$importExitCode = $LASTEXITCODE
|
||||
|
||||
@@ -66,52 +59,50 @@ function ImportRegistryFile {
|
||||
$result.Error = $_.Exception.Message
|
||||
$result.ExitCode = if ($LASTEXITCODE -ne 0) { $LASTEXITCODE } else { 1 }
|
||||
}
|
||||
finally {
|
||||
$global:LASTEXITCODE = 0
|
||||
reg unload "HKU\Default" | Out-Null
|
||||
$unloadExitCode = $LASTEXITCODE
|
||||
if ($unloadExitCode -ne 0 -and -not $result.Error) {
|
||||
$result.Error = "Failed to unload temporary hive HKU\\Default (exit code: $unloadExitCode)"
|
||||
$result.ExitCode = $unloadExitCode
|
||||
}
|
||||
}
|
||||
|
||||
return $result
|
||||
} -ArgumentList @($hiveDatPath, $regFilePath)
|
||||
}
|
||||
else {
|
||||
$regResult = Invoke-NonBlocking -ScriptBlock {
|
||||
param($targetRegFilePath)
|
||||
$global:LASTEXITCODE = 0
|
||||
$output = reg import $targetRegFilePath 2>&1
|
||||
return @{ Output = @($output); ExitCode = $LASTEXITCODE; Error = $null }
|
||||
} -ArgumentList $regFilePath
|
||||
}
|
||||
} -ArgumentList $targetRegFilePath
|
||||
|
||||
$regOutput = @($regResult.Output)
|
||||
$hasSuccess = ($regResult.ExitCode -eq 0) -and -not $regResult.Error
|
||||
|
||||
if ($regOutput) {
|
||||
foreach ($line in $regOutput) {
|
||||
$lineText = if ($line -is [System.Management.Automation.ErrorRecord]) { $line.Exception.Message } else { $line.ToString() }
|
||||
if ($lineText -and $lineText.Length -gt 0) {
|
||||
if ($hasSuccess) {
|
||||
Write-Host $lineText
|
||||
}
|
||||
else {
|
||||
Write-Host $lineText -ForegroundColor Red
|
||||
$regOutput = @($regResult.Output)
|
||||
$hasSuccess = ($regResult.ExitCode -eq 0) -and -not $regResult.Error
|
||||
|
||||
if ($regOutput) {
|
||||
foreach ($line in $regOutput) {
|
||||
$lineText = if ($line -is [System.Management.Automation.ErrorRecord]) { $line.Exception.Message } else { $line.ToString() }
|
||||
if ($lineText -and $lineText.Length -gt 0) {
|
||||
if ($hasSuccess) {
|
||||
Write-Host $lineText
|
||||
}
|
||||
else {
|
||||
Write-Host $lineText -ForegroundColor Red
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $hasSuccess) {
|
||||
$details = if ($regResult.Error) { $regResult.Error } else { "Exit code: $($regResult.ExitCode)" }
|
||||
$errorMessage = "Failed importing registry file '$path'. $details"
|
||||
Write-Host $errorMessage -ForegroundColor Red
|
||||
if (-not $hasSuccess) {
|
||||
$details = if ($regResult.Error) { $regResult.Error } else { "Exit code: $($regResult.ExitCode)" }
|
||||
Write-Warning "reg import failed for '$path'. Falling back to PowerShell registry writer. Details: $details"
|
||||
Invoke-RegistryOperationsFromRegFile -RegFilePath $targetRegFilePath
|
||||
Write-Host "The operation completed successfully via PowerShell registry writer."
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
throw $errorMessage
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
}
|
||||
try {
|
||||
if ($usesOfflineHive) {
|
||||
# Sysprep targets Default user, User targets the specified user. Logged-in users already have their hive mounted under HKU\<SID>.
|
||||
$targetUserName = if ($script:Params.ContainsKey("Sysprep")) { "Default" } else { $script:Params.Item("User") }
|
||||
Invoke-WithTargetUserHive -TargetUserName $targetUserName -ScriptBlock $importScript -ArgumentObject $regFilePath -PassHiveContext
|
||||
}
|
||||
else {
|
||||
& $importScript $regFilePath $null
|
||||
}
|
||||
}
|
||||
catch {
|
||||
$script:RegistryImportFailures++
|
||||
Write-Host $_.Exception.Message -ForegroundColor Red
|
||||
Write-Host ""
|
||||
}
|
||||
}
|
||||
|
||||
447
Scripts/Features/RegistryBackupValidation.ps1
Normal file
447
Scripts/Features/RegistryBackupValidation.ps1
Normal file
@@ -0,0 +1,447 @@
|
||||
function Get-NormalizedSelectedFeatureIdsFromBackup {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Backup
|
||||
)
|
||||
|
||||
$selectedFeatures = New-Object System.Collections.Generic.List[string]
|
||||
$selectedFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
$errors = New-Object System.Collections.Generic.List[string]
|
||||
$hasInvalidSelectedFeatureId = $false
|
||||
|
||||
if (-not $Backup.PSObject.Properties['SelectedFeatures']) {
|
||||
$errors.Add('Missing property: SelectedFeatures')
|
||||
return [PSCustomObject]@{
|
||||
SelectedFeatures = $selectedFeatures.ToArray()
|
||||
Errors = $errors.ToArray()
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($featureId in @($Backup.SelectedFeatures)) {
|
||||
if ($featureId -isnot [string] -or [string]::IsNullOrWhiteSpace([string]$featureId)) {
|
||||
$hasInvalidSelectedFeatureId = $true
|
||||
continue
|
||||
}
|
||||
|
||||
$normalizedFeatureId = [string]$featureId
|
||||
if ($selectedFeatureIds.Add($normalizedFeatureId)) {
|
||||
$selectedFeatures.Add($normalizedFeatureId)
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasInvalidSelectedFeatureId) {
|
||||
$errors.Add('SelectedFeatures must contain non-empty string feature IDs.')
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
SelectedFeatures = $selectedFeatures.ToArray()
|
||||
Errors = $errors.ToArray()
|
||||
}
|
||||
}
|
||||
|
||||
function Get-NormalizedSelectedUndoFeatureIdsFromBackup {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Backup
|
||||
)
|
||||
|
||||
$selectedUndoFeatures = New-Object System.Collections.Generic.List[string]
|
||||
$selectedUndoFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
$errors = New-Object System.Collections.Generic.List[string]
|
||||
|
||||
# SelectedUndoFeatures is optional - only process if present
|
||||
if (-not $Backup.PSObject.Properties['SelectedUndoFeatures']) {
|
||||
return [PSCustomObject]@{
|
||||
SelectedUndoFeatures = $selectedUndoFeatures.ToArray()
|
||||
Errors = $errors.ToArray()
|
||||
}
|
||||
}
|
||||
|
||||
$hasInvalidSelectedUndoFeatureId = $false
|
||||
foreach ($featureId in @($Backup.SelectedUndoFeatures)) {
|
||||
if ($featureId -isnot [string] -or [string]::IsNullOrWhiteSpace([string]$featureId)) {
|
||||
$hasInvalidSelectedUndoFeatureId = $true
|
||||
continue
|
||||
}
|
||||
|
||||
$normalizedFeatureId = [string]$featureId
|
||||
if ($selectedUndoFeatureIds.Add($normalizedFeatureId)) {
|
||||
$selectedUndoFeatures.Add($normalizedFeatureId)
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasInvalidSelectedUndoFeatureId) {
|
||||
$errors.Add('SelectedUndoFeatures must contain non-empty string feature IDs.')
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
SelectedUndoFeatures = $selectedUndoFeatures.ToArray()
|
||||
Errors = $errors.ToArray()
|
||||
}
|
||||
}
|
||||
|
||||
function Normalize-RegistryKeySnapshot {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Snapshot
|
||||
)
|
||||
|
||||
if (-not $Snapshot.PSObject.Properties['Path'] -or [string]::IsNullOrWhiteSpace([string]$Snapshot.Path)) {
|
||||
throw 'Backup validation failed: Registry key snapshot is missing Path.'
|
||||
}
|
||||
|
||||
$exists = $false
|
||||
if ($Snapshot.PSObject.Properties['Exists']) {
|
||||
$exists = [bool]$Snapshot.Exists
|
||||
}
|
||||
|
||||
$values = @()
|
||||
if ($Snapshot.PSObject.Properties['Values']) {
|
||||
foreach ($valueSnapshot in @($Snapshot.Values)) {
|
||||
$valueExists = $true
|
||||
if ($valueSnapshot.PSObject.Properties['Exists']) {
|
||||
$valueExists = [bool]$valueSnapshot.Exists
|
||||
}
|
||||
|
||||
$values += [PSCustomObject]@{
|
||||
Name = [string]$valueSnapshot.Name
|
||||
Exists = $valueExists
|
||||
Kind = if ($valueSnapshot.PSObject.Properties['Kind']) { [string]$valueSnapshot.Kind } else { $null }
|
||||
Data = if ($valueSnapshot.PSObject.Properties['Data']) { $valueSnapshot.Data } else { $null }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$subKeys = @()
|
||||
if ($Snapshot.PSObject.Properties['SubKeys']) {
|
||||
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
|
||||
$subKeys += @(Normalize-RegistryKeySnapshot -Snapshot $subKeySnapshot)
|
||||
}
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
Path = [string]$Snapshot.Path
|
||||
Exists = $exists
|
||||
Values = @($values)
|
||||
SubKeys = @($subKeys)
|
||||
}
|
||||
}
|
||||
|
||||
function Test-RegistryBackupMatchesSelectedFeatures {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
[string[]]$SelectedFeatureIds,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
[string[]]$SelectedUndoFeatureIds,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Target,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
[object[]]$RegistryKeys
|
||||
)
|
||||
|
||||
$errors = New-Object System.Collections.Generic.List[string]
|
||||
|
||||
if (-not $script:Features -or $script:Features.Count -eq 0) {
|
||||
$errors.Add('Unable to validate registry backup allowlist because feature definitions are not loaded.')
|
||||
return $errors.ToArray()
|
||||
}
|
||||
|
||||
$selectedRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedFeatureIds) -IsUndoFeature:$false -Errors $errors)
|
||||
$undoRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedUndoFeatureIds) -IsUndoFeature:$true -Errors $errors)
|
||||
$useSysprepRegFiles = ($Target -eq 'DefaultUserProfile') -or ($Target -like 'User:*')
|
||||
|
||||
$capturePlans = @()
|
||||
if ($errors.Count -eq 0 -and ($selectedRegistryFeatures.Count -gt 0 -or $undoRegistryFeatures.Count -gt 0)) {
|
||||
$capturePlans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures @($selectedRegistryFeatures) -UndoRegistryFeatures @($undoRegistryFeatures) -UseSysprepRegFiles:$useSysprepRegFiles)
|
||||
}
|
||||
|
||||
$planMap = New-RegistryBackupAllowListPlanMap -CapturePlans @($capturePlans)
|
||||
|
||||
if ($planMap.Count -eq 0 -and @($RegistryKeys).Count -gt 0) {
|
||||
$errors.Add('Backup contains registry snapshots but no allowed registry paths were derived from the selected features.')
|
||||
}
|
||||
|
||||
foreach ($rootSnapshot in @($RegistryKeys)) {
|
||||
Test-RegistrySnapshotAgainstAllowList -Snapshot $rootSnapshot -PlanMap $planMap -Errors $errors
|
||||
}
|
||||
|
||||
return $errors.ToArray()
|
||||
}
|
||||
|
||||
function Get-SelectedRegistryFeaturesForBackupValidation {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
[string[]]$SelectedFeatureIds,
|
||||
[Parameter(Mandatory)]
|
||||
[bool]$IsUndoFeature,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
$Errors
|
||||
)
|
||||
|
||||
if ($null -eq $Errors -or -not ($Errors -is [System.Collections.IList])) {
|
||||
throw 'Get-SelectedRegistryFeaturesForBackupValidation requires Errors to be a mutable list collection.'
|
||||
}
|
||||
|
||||
$selectedRegistryFeatures = New-Object System.Collections.Generic.List[object]
|
||||
foreach ($featureId in @($SelectedFeatureIds)) {
|
||||
if (-not $script:Features.ContainsKey($featureId)) {
|
||||
$Errors.Add("Selected feature '$featureId' was not found in the current feature catalog.")
|
||||
continue
|
||||
}
|
||||
|
||||
$feature = $script:Features[$featureId]
|
||||
if (-not $feature) {
|
||||
continue
|
||||
}
|
||||
|
||||
# For undo features, check RegistryUndoKey if present (real features)
|
||||
# Otherwise check RegistryKey (for synthetic features from backup capture)
|
||||
$registryKeyToUse = if ($IsUndoFeature) {
|
||||
$key = [string]$feature.RegistryUndoKey
|
||||
if (-not [string]::IsNullOrWhiteSpace($key)) {
|
||||
$key
|
||||
}
|
||||
else {
|
||||
[string]$feature.RegistryKey
|
||||
}
|
||||
}
|
||||
else {
|
||||
[string]$feature.RegistryKey
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace($registryKeyToUse)) {
|
||||
$selectedRegistryFeatures.Add($feature)
|
||||
}
|
||||
}
|
||||
|
||||
return $selectedRegistryFeatures.ToArray()
|
||||
}
|
||||
|
||||
function New-RegistryBackupAllowListPlanMap {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
[object[]]$CapturePlans
|
||||
)
|
||||
|
||||
$planMap = @{}
|
||||
foreach ($plan in @($CapturePlans)) {
|
||||
$normalizedPath = Get-NormalizedRegistryPathKey -Path $plan.Path
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedPath)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$planMap[$normalizedPath] = [PSCustomObject]@{
|
||||
Path = $plan.Path
|
||||
NormalizedPath = $normalizedPath
|
||||
IncludeSubKeys = [bool]$plan.IncludeSubKeys
|
||||
CaptureAllValues = [bool]$plan.CaptureAllValues
|
||||
ValueNames = ConvertTo-RegistryValueNameSet -ValueNames @($plan.ValueNames)
|
||||
}
|
||||
}
|
||||
|
||||
return $planMap
|
||||
}
|
||||
|
||||
function ConvertTo-RegistryValueNameSet {
|
||||
param(
|
||||
[AllowEmptyCollection()]
|
||||
[string[]]$ValueNames
|
||||
)
|
||||
|
||||
$valueNameSet = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($valueName in @($ValueNames)) {
|
||||
$null = $valueNameSet.Add([string]$valueName)
|
||||
}
|
||||
|
||||
return $valueNameSet
|
||||
}
|
||||
|
||||
function Test-RegistrySnapshotAgainstAllowList {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Snapshot,
|
||||
[Parameter(Mandatory)]
|
||||
[hashtable]$PlanMap,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowEmptyCollection()]
|
||||
[System.Collections.Generic.List[string]]$Errors
|
||||
)
|
||||
|
||||
$snapshotPath = [string]$Snapshot.Path
|
||||
$normalizedPath = Get-NormalizedRegistryPathKey -Path $snapshotPath
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedPath)) {
|
||||
$Errors.Add("Backup contains unsupported registry path '$snapshotPath'.")
|
||||
return
|
||||
}
|
||||
|
||||
$planMatch = Find-RegistryAllowListPlanMatch -NormalizedPath $normalizedPath -PlanMap $PlanMap
|
||||
if ($null -eq $planMatch) {
|
||||
$Errors.Add("Backup contains unexpected registry path '$snapshotPath' that is not allowed by SelectedFeatures.")
|
||||
return
|
||||
}
|
||||
|
||||
foreach ($valueSnapshot in @($Snapshot.Values)) {
|
||||
$valueName = Get-NormalizedRegistryValueName -ValueName $valueSnapshot.Name
|
||||
$valueExists = [bool]$valueSnapshot.Exists
|
||||
|
||||
if (-not (Test-RegistryValueAllowedByPlan -PlanMatch $planMatch -ValueName $valueName)) {
|
||||
$Errors.Add("Backup contains unexpected value '$valueName' under '$snapshotPath'.")
|
||||
}
|
||||
|
||||
$kindName = if ($valueSnapshot.PSObject.Properties['Kind']) { [string]$valueSnapshot.Kind } else { '' }
|
||||
$valueReference = Get-RegistryValueReferenceForError -SnapshotPath $snapshotPath -ValueName $valueName
|
||||
if ($valueExists) {
|
||||
if (-not (Test-RegistryValueKindNameSupported -KindName $kindName)) {
|
||||
$Errors.Add("Backup contains unsupported registry value kind '$kindName' for '$valueReference'.")
|
||||
}
|
||||
}
|
||||
elseif (-not [string]::IsNullOrWhiteSpace($kindName)) {
|
||||
$Errors.Add("Backup value '$valueReference' must not define Kind when Exists is false.")
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
|
||||
Test-RegistrySnapshotAgainstAllowList -Snapshot $subKeySnapshot -PlanMap $PlanMap -Errors $Errors
|
||||
}
|
||||
}
|
||||
|
||||
function Test-RegistryValueAllowedByPlan {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$PlanMatch,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowNull()]
|
||||
[AllowEmptyString()]
|
||||
[string]$ValueName
|
||||
)
|
||||
|
||||
$ValueName = Get-NormalizedRegistryValueName -ValueName $ValueName
|
||||
|
||||
if ($PlanMatch.CaptureAllValues -or $PlanMatch.IsDescendant) {
|
||||
return $true
|
||||
}
|
||||
|
||||
return $PlanMatch.ValueNames.Contains($ValueName)
|
||||
}
|
||||
|
||||
function Get-RegistryValueReferenceForError {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$SnapshotPath,
|
||||
[Parameter(Mandatory)]
|
||||
[AllowNull()]
|
||||
[AllowEmptyString()]
|
||||
[string]$ValueName
|
||||
)
|
||||
|
||||
$ValueName = Get-NormalizedRegistryValueName -ValueName $ValueName
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($ValueName)) {
|
||||
return "$SnapshotPath\\(Default)"
|
||||
}
|
||||
|
||||
return "$SnapshotPath\\$ValueName"
|
||||
}
|
||||
|
||||
function Get-NormalizedRegistryValueName {
|
||||
param(
|
||||
[AllowNull()]
|
||||
[AllowEmptyString()]
|
||||
[object]$ValueName
|
||||
)
|
||||
|
||||
if ($null -eq $ValueName) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return [string]$ValueName
|
||||
}
|
||||
|
||||
function Find-RegistryAllowListPlanMatch {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$NormalizedPath,
|
||||
[Parameter(Mandatory)]
|
||||
[hashtable]$PlanMap
|
||||
)
|
||||
|
||||
if ($PlanMap.ContainsKey($NormalizedPath)) {
|
||||
$plan = $PlanMap[$NormalizedPath]
|
||||
return [PSCustomObject]@{
|
||||
IsDescendant = $false
|
||||
CaptureAllValues = [bool]$plan.CaptureAllValues
|
||||
ValueNames = $plan.ValueNames
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($plan in @($PlanMap.Values)) {
|
||||
if (-not [bool]$plan.IncludeSubKeys) {
|
||||
continue
|
||||
}
|
||||
|
||||
$subKeyPrefix = "$($plan.NormalizedPath)\\"
|
||||
if ($NormalizedPath.StartsWith($subKeyPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
return [PSCustomObject]@{
|
||||
IsDescendant = $true
|
||||
CaptureAllValues = $true
|
||||
ValueNames = $plan.ValueNames
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Get-NormalizedRegistryPathKey {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Path
|
||||
)
|
||||
|
||||
$parts = Split-RegistryPath -path $Path
|
||||
if (-not $parts) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$hiveName = [string]$parts.Hive
|
||||
if ([string]::IsNullOrWhiteSpace($hiveName)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$normalizedHive = $hiveName.ToUpperInvariant()
|
||||
$subKey = [string]$parts.SubKey
|
||||
if ([string]::IsNullOrWhiteSpace($subKey)) {
|
||||
return $normalizedHive
|
||||
}
|
||||
|
||||
$normalizedSubKey = ($subKey -replace '/', '\\').Trim('\')
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedSubKey)) {
|
||||
return $normalizedHive
|
||||
}
|
||||
|
||||
return "$normalizedHive\\$normalizedSubKey"
|
||||
}
|
||||
|
||||
function Test-RegistryValueKindNameSupported {
|
||||
param(
|
||||
[string]$KindName
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($KindName)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
try {
|
||||
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
|
||||
return $kind -ne [Microsoft.Win32.RegistryValueKind]::Unknown
|
||||
}
|
||||
catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
# Credit: https://lazyadmin.nl/win-11/customize-windows-11-start-menu-layout/
|
||||
function ReplaceStartMenuForAllUsers {
|
||||
param (
|
||||
$startMenuTemplate = "$script:AssetsPath/Start/start2.bin"
|
||||
$startMenuTemplate = "$script:AssetsPath\Start\start2.bin"
|
||||
)
|
||||
|
||||
Write-Host "> Removing all pinned apps from the start menu for all users..."
|
||||
@@ -16,7 +16,7 @@ function ReplaceStartMenuForAllUsers {
|
||||
|
||||
# Get path to start menu file for all users
|
||||
$userPathString = GetUserDirectory -userName "*" -fileName "AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState"
|
||||
$usersStartMenuPaths = get-childitem -path $userPathString
|
||||
$usersStartMenuPaths = Get-ChildItem -Path $userPathString -ErrorAction SilentlyContinue
|
||||
|
||||
# Go through all users and replace the start menu file
|
||||
ForEach ($startMenuPath in $usersStartMenuPaths) {
|
||||
@@ -39,17 +39,17 @@ function ReplaceStartMenuForAllUsers {
|
||||
}
|
||||
|
||||
|
||||
# Replace the startmenu for all users, when using the default startmenuTemplate this clears all pinned apps
|
||||
# Replace the startmenu at the specified location, when using the default startmenuTemplate this clears all pinned apps
|
||||
# Credit: https://lazyadmin.nl/win-11/customize-windows-11-start-menu-layout/
|
||||
function ReplaceStartMenu {
|
||||
param (
|
||||
$startMenuTemplate = "$script:AssetsPath/Start/start2.bin",
|
||||
$startMenuTemplate = "$script:AssetsPath\Start\start2.bin",
|
||||
$startMenuBinFile = "$env:LOCALAPPDATA\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState\start2.bin"
|
||||
)
|
||||
|
||||
# Change path to correct user if a user was specified
|
||||
if ($script:Params.ContainsKey("User")) {
|
||||
$startMenuBinFile = GetUserDirectory -userName "$(GetUserName)" -fileName "AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState\start2.bin" -exitIfPathNotFound $false
|
||||
$startMenuBinFile = GetStartMenuBinPathForUser -UserName (GetUserName)
|
||||
}
|
||||
|
||||
# Check if template bin file exists
|
||||
@@ -63,7 +63,7 @@ function ReplaceStartMenu {
|
||||
return
|
||||
}
|
||||
|
||||
$userName = [regex]::Match($startMenuBinFile, '(?:Users\\)([^\\]+)(?:\\AppData)').Groups[1].Value
|
||||
$userName = GetStartMenuUserNameFromPath -StartMenuBinFile $startMenuBinFile
|
||||
|
||||
$backupBinFile = $startMenuBinFile + ".bak"
|
||||
|
||||
@@ -80,4 +80,142 @@ function ReplaceStartMenu {
|
||||
Copy-Item -Path $startMenuTemplate -Destination $startMenuBinFile -Force
|
||||
|
||||
Write-Host "Replaced start menu for user $userName"
|
||||
}
|
||||
|
||||
function GetStartMenuBinPathForUser {
|
||||
param(
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($UserName)) {
|
||||
return "$env:LOCALAPPDATA\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState\start2.bin"
|
||||
}
|
||||
|
||||
return (GetUserDirectory -userName $UserName -fileName "AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState\start2.bin" -exitIfPathNotFound $false)
|
||||
}
|
||||
|
||||
function GetStartMenuUserNameFromPath {
|
||||
param(
|
||||
[string]$StartMenuBinFile
|
||||
)
|
||||
|
||||
$resolvedUserName = [regex]::Match($StartMenuBinFile, '(?:Users\\)([^\\]+)(?:\\AppData)').Groups[1].Value
|
||||
if ([string]::IsNullOrWhiteSpace($resolvedUserName)) {
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
return $resolvedUserName
|
||||
}
|
||||
|
||||
|
||||
|
||||
function RestoreStartMenuFromBackup {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$StartMenuBinFile,
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$BackupFilePath
|
||||
)
|
||||
|
||||
$userName = GetStartMenuUserNameFromPath -StartMenuBinFile $StartMenuBinFile
|
||||
$backupBinFile = if ([string]::IsNullOrWhiteSpace($BackupFilePath)) {
|
||||
$StartMenuBinFile + '.bak'
|
||||
}
|
||||
else {
|
||||
$BackupFilePath
|
||||
}
|
||||
$currentBinBackup = $StartMenuBinFile + '.restore.bak'
|
||||
|
||||
if (-not (Test-Path -LiteralPath $backupBinFile)) {
|
||||
return [PSCustomObject]@{
|
||||
UserName = $userName
|
||||
Result = $false
|
||||
Message = "No start menu backup file found for user $userName."
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (Test-Path -LiteralPath $StartMenuBinFile) {
|
||||
Move-Item -Path $StartMenuBinFile -Destination $currentBinBackup -Force
|
||||
}
|
||||
|
||||
Copy-Item -Path $backupBinFile -Destination $StartMenuBinFile -Force
|
||||
return [PSCustomObject]@{
|
||||
UserName = $userName
|
||||
Result = $true
|
||||
Message = "Restored start menu for user $userName."
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return [PSCustomObject]@{
|
||||
UserName = $userName
|
||||
Result = $false
|
||||
Message = "Failed to restore start menu for user $userName. $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function RestoreStartMenu {
|
||||
param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$BackupFilePath
|
||||
)
|
||||
|
||||
$targetUserName = GetUserName
|
||||
$startMenuBinFile = GetStartMenuBinPathForUser -UserName $targetUserName
|
||||
|
||||
Write-Host "Restoring start menu for user $targetUserName from backup..."
|
||||
|
||||
return RestoreStartMenuFromBackup -StartMenuBinFile $startMenuBinFile -BackupFilePath $BackupFilePath
|
||||
}
|
||||
|
||||
function RestoreStartMenuForAllUsers {
|
||||
param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[string]$BackupFilePath
|
||||
)
|
||||
|
||||
$userPathString = GetUserDirectory -userName "*" -fileName "AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState"
|
||||
$usersStartMenuPaths = Get-ChildItem -Path $userPathString -ErrorAction SilentlyContinue
|
||||
$results = @()
|
||||
|
||||
Write-Host "Restoring start menu for all users from backup..."
|
||||
|
||||
foreach ($startMenuPath in $usersStartMenuPaths) {
|
||||
$startMenuBinFile = Join-Path $startMenuPath.FullName 'start2.bin'
|
||||
$results += RestoreStartMenuFromBackup -StartMenuBinFile $startMenuBinFile -BackupFilePath $BackupFilePath
|
||||
}
|
||||
|
||||
$defaultStartMenuPath = GetUserDirectory -userName "Default" -fileName "AppData\Local\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState" -exitIfPathNotFound $false
|
||||
|
||||
if (Test-Path $defaultStartMenuPath) {
|
||||
$defaultStartMenuBinFile = Join-Path $defaultStartMenuPath 'start2.bin'
|
||||
if (Test-Path -LiteralPath $defaultStartMenuBinFile) {
|
||||
try {
|
||||
Remove-Item -LiteralPath $defaultStartMenuBinFile -Force
|
||||
$results += [PSCustomObject]@{
|
||||
UserName = 'Default'
|
||||
Result = $true
|
||||
Message = 'Removed start2.bin for the default user profile.'
|
||||
}
|
||||
}
|
||||
catch {
|
||||
$results += [PSCustomObject]@{
|
||||
UserName = 'Default'
|
||||
Result = $false
|
||||
Message = "Failed to remove start2.bin for the default user profile. $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($results.Count -eq 0) {
|
||||
$results += [PSCustomObject]@{
|
||||
UserName = 'unknown'
|
||||
Result = $false
|
||||
Message = 'No user start menu locations were found.'
|
||||
}
|
||||
}
|
||||
|
||||
return $results
|
||||
}
|
||||
@@ -1,8 +1,13 @@
|
||||
# Restart the Windows Explorer process
|
||||
function RestartExplorer {
|
||||
# Restarting Explorer while running in Sysprep or User context is not necessary
|
||||
if ($script:Params.ContainsKey("Sysprep") -or $script:Params.ContainsKey("User")) {
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "> Attempting to restart the Windows Explorer process to apply all changes..."
|
||||
|
||||
if ($script:Params.ContainsKey("Sysprep") -or $script:Params.ContainsKey("User") -or $script:Params.ContainsKey("NoRestartExplorer")) {
|
||||
if ($script:Params.ContainsKey("NoRestartExplorer")) {
|
||||
Write-Host "Explorer process restart was skipped, please manually reboot your PC to apply all changes" -ForegroundColor Yellow
|
||||
return
|
||||
}
|
||||
@@ -10,7 +15,7 @@ function RestartExplorer {
|
||||
foreach ($paramKey in $script:Params.Keys) {
|
||||
if ($script:Features.ContainsKey($paramKey) -and $script:Features[$paramKey].RequiresReboot -eq $true) {
|
||||
$feature = $script:Features[$paramKey]
|
||||
Write-Host "Warning: '$($feature.Action)' requires a reboot to take full effect" -ForegroundColor Yellow
|
||||
Write-Host "Warning: '$($feature.Label)' requires a reboot to take full effect" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
224
Scripts/Features/RestoreRegistryApplyState.ps1
Normal file
224
Scripts/Features/RestoreRegistryApplyState.ps1
Normal file
@@ -0,0 +1,224 @@
|
||||
function Invoke-WithLoadedRestoreHive {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Target,
|
||||
[Parameter(Mandatory)]
|
||||
[scriptblock]$ScriptBlock,
|
||||
$ArgumentObject = $null
|
||||
)
|
||||
|
||||
$targetUserName = if ($Target -eq 'DefaultUserProfile') {
|
||||
'Default'
|
||||
}
|
||||
elseif ($Target -like 'User:*') {
|
||||
$userName = $Target.Substring(5)
|
||||
if ([string]::IsNullOrWhiteSpace($userName)) {
|
||||
throw 'Invalid backup target format for user restore.'
|
||||
}
|
||||
$userName
|
||||
}
|
||||
else {
|
||||
throw "Unsupported backup target '$Target'."
|
||||
}
|
||||
|
||||
Invoke-WithTargetUserHive -TargetUserName $targetUserName -ScriptBlock $ScriptBlock -ArgumentObject $ArgumentObject
|
||||
}
|
||||
|
||||
function Restore-RegistryKeySnapshot {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Snapshot
|
||||
)
|
||||
|
||||
$registryParts = Split-RegistryPath -path $Snapshot.Path
|
||||
if (-not $registryParts) {
|
||||
throw "Unsupported registry path in backup: $($Snapshot.Path)"
|
||||
}
|
||||
|
||||
$rootKey = Get-RegistryRootKey -hiveName $registryParts.Hive
|
||||
if (-not $rootKey) {
|
||||
throw "Unsupported registry hive in backup: $($registryParts.Hive)"
|
||||
}
|
||||
|
||||
$subKeyPath = $registryParts.SubKey
|
||||
if ([string]::IsNullOrWhiteSpace($subKeyPath)) {
|
||||
throw "Unsupported root-level registry path in backup: $($Snapshot.Path)"
|
||||
}
|
||||
|
||||
if (-not $Snapshot.Exists) {
|
||||
Remove-RegistrySubKeyTreeIfExists -RootKey $rootKey -SubKeyPath $subKeyPath
|
||||
return
|
||||
}
|
||||
|
||||
$forceFullTree = @($Snapshot.SubKeys).Count -gt 0
|
||||
if ($forceFullTree) {
|
||||
Remove-RegistrySubKeyTreeIfExists -RootKey $rootKey -SubKeyPath $subKeyPath
|
||||
}
|
||||
|
||||
$key = $rootKey.CreateSubKey($subKeyPath)
|
||||
if ($null -eq $key) {
|
||||
throw "Unable to create or open registry key '$($Snapshot.Path)'"
|
||||
}
|
||||
|
||||
try {
|
||||
foreach ($valueSnapshot in @($Snapshot.Values)) {
|
||||
Restore-RegistryValueSnapshot -RegistryKey $key -Snapshot $valueSnapshot
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$key.Close()
|
||||
}
|
||||
|
||||
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
|
||||
Restore-RegistryKeySnapshot -Snapshot $subKeySnapshot
|
||||
}
|
||||
}
|
||||
|
||||
function Restore-RegistryValueSnapshot {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Microsoft.Win32.RegistryKey]$RegistryKey,
|
||||
[Parameter(Mandatory)]
|
||||
$Snapshot
|
||||
)
|
||||
|
||||
$valueName = if ($null -ne $Snapshot.Name) { [string]$Snapshot.Name } else { '' }
|
||||
|
||||
if (-not [bool]$Snapshot.Exists) {
|
||||
try {
|
||||
$RegistryKey.DeleteValue($valueName, $false)
|
||||
}
|
||||
catch {
|
||||
throw "Failed deleting registry value '$valueName' in '$($RegistryKey.Name)': $($_.Exception.Message)"
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
$valueKind = Convert-RegistryValueKindFromBackup -KindName $Snapshot.Kind
|
||||
$normalizedData = Convert-RegistryValueDataFromBackup -Kind $valueKind -Data $Snapshot.Data
|
||||
|
||||
try {
|
||||
$RegistryKey.SetValue($valueName, $normalizedData, $valueKind)
|
||||
}
|
||||
catch {
|
||||
$retryBytes = Convert-BackupDataToByteArray -Data $Snapshot.Data
|
||||
if ($null -ne $retryBytes) {
|
||||
try {
|
||||
$RegistryKey.SetValue($valueName, $retryBytes, [Microsoft.Win32.RegistryValueKind]::Binary)
|
||||
return
|
||||
}
|
||||
catch {
|
||||
# Fall through to original error message for context.
|
||||
}
|
||||
}
|
||||
|
||||
throw "Failed setting registry value '$valueName' in '$($RegistryKey.Name)': $($_.Exception.Message)"
|
||||
}
|
||||
}
|
||||
|
||||
function Convert-RegistryValueKindFromBackup {
|
||||
param(
|
||||
[string]$KindName
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($KindName)) {
|
||||
return [Microsoft.Win32.RegistryValueKind]::String
|
||||
}
|
||||
|
||||
try {
|
||||
return [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
|
||||
}
|
||||
catch {
|
||||
throw "Unsupported registry value kind in backup: $KindName"
|
||||
}
|
||||
}
|
||||
|
||||
function Convert-RegistryValueDataFromBackup {
|
||||
param(
|
||||
[Microsoft.Win32.RegistryValueKind]$Kind,
|
||||
$Data
|
||||
)
|
||||
|
||||
switch ($Kind) {
|
||||
([Microsoft.Win32.RegistryValueKind]::DWord) {
|
||||
$unsigned = [uint32]$Data
|
||||
return [BitConverter]::ToInt32([BitConverter]::GetBytes($unsigned), 0)
|
||||
}
|
||||
([Microsoft.Win32.RegistryValueKind]::QWord) {
|
||||
$unsigned = [uint64]$Data
|
||||
return [BitConverter]::ToInt64([BitConverter]::GetBytes($unsigned), 0)
|
||||
}
|
||||
([Microsoft.Win32.RegistryValueKind]::MultiString) { return @($Data | ForEach-Object { [string]$_ }) }
|
||||
([Microsoft.Win32.RegistryValueKind]::Binary) {
|
||||
$bytes = Convert-BackupDataToByteArray -Data $Data
|
||||
if ($null -eq $bytes) {
|
||||
return (New-Object byte[] 0)
|
||||
}
|
||||
return $bytes
|
||||
}
|
||||
([Microsoft.Win32.RegistryValueKind]::None) { return $null }
|
||||
default {
|
||||
if ($null -ne $Data) {
|
||||
return [string]$Data
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Convert-BackupDataToByteArray {
|
||||
param(
|
||||
$Data
|
||||
)
|
||||
|
||||
if ($null -eq $Data) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if ($Data -is [byte[]]) {
|
||||
return ,$Data
|
||||
}
|
||||
|
||||
$items = @($Data)
|
||||
if ($items.Count -eq 0) {
|
||||
return ,(New-Object byte[] 0)
|
||||
}
|
||||
|
||||
foreach ($item in $items) {
|
||||
if ($item -isnot [ValueType] -and $item -isnot [string]) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$parsed = 0
|
||||
if (-not [int]::TryParse([string]$item, [ref]$parsed)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if ($parsed -lt 0 -or $parsed -gt 255) {
|
||||
return $null
|
||||
}
|
||||
}
|
||||
|
||||
$bytes = New-Object byte[] $items.Count
|
||||
for ($i = 0; $i -lt $items.Count; $i++) {
|
||||
$bytes[$i] = [byte][int]$items[$i]
|
||||
}
|
||||
|
||||
return ,$bytes
|
||||
}
|
||||
|
||||
function Remove-RegistrySubKeyTreeIfExists {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Microsoft.Win32.RegistryKey]$RootKey,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$SubKeyPath
|
||||
)
|
||||
|
||||
$existing = $RootKey.OpenSubKey($SubKeyPath, $false)
|
||||
if ($existing) {
|
||||
$existing.Close()
|
||||
$RootKey.DeleteSubKeyTree($SubKeyPath, $false)
|
||||
}
|
||||
}
|
||||
156
Scripts/Features/RestoreRegistryBackup.ps1
Normal file
156
Scripts/Features/RestoreRegistryBackup.ps1
Normal file
@@ -0,0 +1,156 @@
|
||||
function Load-RegistryBackupFromFile {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FilePath
|
||||
)
|
||||
|
||||
if (-not (Test-Path -LiteralPath $FilePath)) {
|
||||
throw "Backup file was not found: $FilePath"
|
||||
}
|
||||
|
||||
try {
|
||||
$rawBackup = Get-Content -LiteralPath $FilePath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
throw "Failed to read backup file '$FilePath'. The file is not valid JSON."
|
||||
}
|
||||
|
||||
return Normalize-RegistryBackup -Backup $rawBackup
|
||||
}
|
||||
|
||||
function Normalize-RegistryBackup {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Backup
|
||||
)
|
||||
|
||||
$errors = New-Object System.Collections.Generic.List[string]
|
||||
|
||||
if (-not $Backup.PSObject.Properties['Version']) {
|
||||
$errors.Add('Missing property: Version')
|
||||
}
|
||||
elseif ([string]$Backup.Version -ne '1.0') {
|
||||
$errors.Add("Unsupported backup version '$($Backup.Version)'.")
|
||||
}
|
||||
|
||||
if (-not $Backup.PSObject.Properties['BackupType']) {
|
||||
$errors.Add('Missing property: BackupType')
|
||||
}
|
||||
elseif ([string]$Backup.BackupType -ne 'RegistryState') {
|
||||
$errors.Add("Unsupported BackupType '$($Backup.BackupType)'.")
|
||||
}
|
||||
|
||||
$normalizedTarget = ''
|
||||
if (-not $Backup.PSObject.Properties['Target'] -or [string]::IsNullOrWhiteSpace([string]$Backup.Target)) {
|
||||
$errors.Add('Missing property: Target')
|
||||
}
|
||||
else {
|
||||
$normalizedTarget = [string]$Backup.Target
|
||||
|
||||
if ($normalizedTarget -eq 'DefaultUserProfile') {
|
||||
# Valid target format.
|
||||
}
|
||||
elseif ($normalizedTarget -like 'User:*') {
|
||||
$targetUserName = $normalizedTarget.Substring(5)
|
||||
$targetValidation = Test-TargetUserName -UserName $targetUserName
|
||||
if (-not $targetValidation.IsValid) {
|
||||
$errors.Add("Invalid user '$normalizedTarget'")
|
||||
}
|
||||
}
|
||||
elseif ($normalizedTarget -like 'CurrentUser:*') {
|
||||
$targetCurrentUserName = $normalizedTarget.Substring(12)
|
||||
if ([string]::IsNullOrWhiteSpace($targetCurrentUserName) -or ($targetCurrentUserName -ne $env:USERNAME)) {
|
||||
$errors.Add("Backup was made for '$targetCurrentUserName', this does not match current user '$env:USERNAME'.")
|
||||
}
|
||||
}
|
||||
else {
|
||||
$errors.Add("Unsupported Target '$normalizedTarget'.")
|
||||
}
|
||||
}
|
||||
|
||||
$registryKeys = @()
|
||||
if (-not $Backup.PSObject.Properties['RegistryKeys']) {
|
||||
$errors.Add('Missing property: RegistryKeys')
|
||||
}
|
||||
else {
|
||||
$registryKeys = @($Backup.RegistryKeys)
|
||||
}
|
||||
|
||||
$normalizedKeys = @()
|
||||
foreach ($keySnapshot in $registryKeys) {
|
||||
$normalizedKeys += @(Normalize-RegistryKeySnapshot -Snapshot $keySnapshot)
|
||||
}
|
||||
|
||||
$selectedFeatureParseResult = Get-NormalizedSelectedFeatureIdsFromBackup -Backup $Backup
|
||||
$selectedFeatures = @($selectedFeatureParseResult.SelectedFeatures)
|
||||
foreach ($selectedFeatureParseError in @($selectedFeatureParseResult.Errors)) {
|
||||
$errors.Add([string]$selectedFeatureParseError)
|
||||
}
|
||||
|
||||
$selectedUndoFeatureParseResult = Get-NormalizedSelectedUndoFeatureIdsFromBackup -Backup $Backup
|
||||
$selectedUndoFeatures = @($selectedUndoFeatureParseResult.SelectedUndoFeatures)
|
||||
foreach ($selectedUndoFeatureParseError in @($selectedUndoFeatureParseResult.Errors)) {
|
||||
$errors.Add([string]$selectedUndoFeatureParseError)
|
||||
}
|
||||
|
||||
$allSelectedFeatures = @($selectedFeatures) + @($selectedUndoFeatures)
|
||||
if ($allSelectedFeatures.Count -eq 0) {
|
||||
$errors.Add('Backup must contain at least one feature ID in SelectedFeatures or SelectedUndoFeatures.')
|
||||
}
|
||||
$allowListValidationErrors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @($selectedFeatures) -SelectedUndoFeatureIds @($selectedUndoFeatures) -Target $normalizedTarget -RegistryKeys @($normalizedKeys))
|
||||
foreach ($allowListValidationError in $allowListValidationErrors) {
|
||||
$errors.Add([string]$allowListValidationError)
|
||||
}
|
||||
|
||||
if ($errors.Count -gt 0) {
|
||||
Write-Error "Backup validation failed: $($errors -join ' ')"
|
||||
if ($errors.Count -eq 1) {
|
||||
throw ("Validation failed: $($errors[0])")
|
||||
}
|
||||
else {
|
||||
throw ("Validation failed with $($errors.Count) errors. See console output for details.")
|
||||
}
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
Version = [string]$Backup.Version
|
||||
BackupType = [string]$Backup.BackupType
|
||||
CreatedAt = [string]$Backup.CreatedAt
|
||||
CreatedBy = [string]$Backup.CreatedBy
|
||||
ComputerName = [string]$Backup.ComputerName
|
||||
Target = $normalizedTarget
|
||||
SelectedFeatures = @($selectedFeatures)
|
||||
SelectedUndoFeatures = @($selectedUndoFeatures)
|
||||
RegistryKeys = @($normalizedKeys)
|
||||
}
|
||||
}
|
||||
|
||||
function Restore-RegistryBackupState {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Backup
|
||||
)
|
||||
|
||||
$friendlyTarget = GetFriendlyRegistryBackupTarget -Target ([string]$Backup.Target)
|
||||
|
||||
$restoreAction = {
|
||||
param($normalizedBackup)
|
||||
|
||||
Write-Host "Applying registry restore from $(@($normalizedBackup.RegistryKeys).Count) root snapshot(s)."
|
||||
foreach ($rootSnapshot in @($normalizedBackup.RegistryKeys)) {
|
||||
Restore-RegistryKeySnapshot -Snapshot $rootSnapshot
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Starting restore for $friendlyTarget."
|
||||
|
||||
if ($Backup.Target -eq 'DefaultUserProfile' -or $Backup.Target -like 'User:*') {
|
||||
Write-Host "Restore requires loading target user hive."
|
||||
Invoke-WithLoadedRestoreHive -Target $Backup.Target -ScriptBlock $restoreAction -ArgumentObject $Backup
|
||||
Write-Host "Restore completed for $friendlyTarget."
|
||||
return
|
||||
}
|
||||
|
||||
& $restoreAction $Backup
|
||||
Write-Host "Restore completed for $friendlyTarget."
|
||||
}
|
||||
49
Scripts/Features/WindowsOptionalFeatures.ps1
Normal file
49
Scripts/Features/WindowsOptionalFeatures.ps1
Normal file
@@ -0,0 +1,49 @@
|
||||
# Enables a Windows optional feature and pipes its output to the console
|
||||
function EnableWindowsFeature {
|
||||
param (
|
||||
[string]$FeatureName
|
||||
)
|
||||
|
||||
$result = Invoke-NonBlocking -ScriptBlock {
|
||||
param($name)
|
||||
Enable-WindowsOptionalFeature -Online -FeatureName $name -All -NoRestart
|
||||
} -ArgumentList $FeatureName
|
||||
|
||||
$dismResult = @($result) | Where-Object { $_ -is [Microsoft.Dism.Commands.ImageObject] }
|
||||
if ($dismResult) {
|
||||
Write-Host ($dismResult | Out-String).Trim()
|
||||
}
|
||||
}
|
||||
|
||||
# Disables a Windows optional feature and pipes its output to the console
|
||||
function DisableWindowsFeature {
|
||||
param (
|
||||
[string]$FeatureName
|
||||
)
|
||||
|
||||
$result = Invoke-NonBlocking -ScriptBlock {
|
||||
param($name)
|
||||
Disable-WindowsOptionalFeature -Online -FeatureName $name -NoRestart
|
||||
} -ArgumentList $FeatureName
|
||||
|
||||
$dismResult = @($result) | Where-Object { $_ -is [Microsoft.Dism.Commands.ImageObject] }
|
||||
if ($dismResult) {
|
||||
Write-Host ($dismResult | Out-String).Trim()
|
||||
}
|
||||
}
|
||||
|
||||
function Test-WindowsOptionalFeatureEnabled {
|
||||
param (
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FeatureName
|
||||
)
|
||||
|
||||
try {
|
||||
$feature = Get-WindowsOptionalFeature -Online -FeatureName $FeatureName -ErrorAction Stop
|
||||
}
|
||||
catch {
|
||||
return $false
|
||||
}
|
||||
|
||||
return ($feature.State -eq 'Enabled')
|
||||
}
|
||||
@@ -6,11 +6,14 @@ function SaveToFile {
|
||||
[hashtable]$Config,
|
||||
|
||||
[Parameter(Mandatory=$true)]
|
||||
[string]$FilePath
|
||||
[string]$FilePath,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[int]$MaxDepth = 10
|
||||
)
|
||||
|
||||
try {
|
||||
$Config | ConvertTo-Json -Depth 10 | Set-Content -Path $FilePath -Encoding UTF8
|
||||
$Config | ConvertTo-Json -Depth $MaxDepth | Set-Content -Path $FilePath -Encoding UTF8
|
||||
return $true
|
||||
}
|
||||
catch {
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
# Checks if the system is set to use dark mode for apps
|
||||
function GetSystemUsesDarkMode {
|
||||
try {
|
||||
return (Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize' -Name 'AppsUseLightTheme').AppsUseLightTheme -eq 0
|
||||
$personalizeKey = Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize'
|
||||
|
||||
if ($null -eq $personalizeKey) {
|
||||
Write-Host "WARNING: Unable to retrieve personalization settings." -ForegroundColor Yellow
|
||||
return $false
|
||||
}
|
||||
|
||||
return $personalizeKey.AppsUseLightTheme -eq 0
|
||||
}
|
||||
catch {
|
||||
return $false
|
||||
|
||||
540
Scripts/GUI/MainWindow-AppSelection.ps1
Normal file
540
Scripts/GUI/MainWindow-AppSelection.ps1
Normal file
@@ -0,0 +1,540 @@
|
||||
# MainWindow-AppSelection.ps1
|
||||
# App-selection panel functions: tri-state helpers, sorting, search/highlight, app loading, preset management, and removal scope.
|
||||
|
||||
function Add-TriStateClickBehavior {
|
||||
param([System.Windows.Controls.CheckBox]$CheckBox)
|
||||
|
||||
if (-not $CheckBox -or -not $CheckBox.IsThreeState) { return }
|
||||
|
||||
if (-not $CheckBox.PSObject.Properties['WasIndeterminateBeforeClick']) {
|
||||
Add-Member -InputObject $CheckBox -MemberType NoteProperty -Name 'WasIndeterminateBeforeClick' -Value $false
|
||||
}
|
||||
|
||||
$CheckBox.Add_PreviewMouseLeftButtonDown({
|
||||
$this.WasIndeterminateBeforeClick = ($this.IsChecked -eq [System.Nullable[bool]]$null)
|
||||
})
|
||||
}
|
||||
|
||||
function ConvertTo-NormalizedCheckboxState {
|
||||
param([System.Windows.Controls.CheckBox]$CheckBox)
|
||||
|
||||
if ($CheckBox.PSObject.Properties['WasIndeterminateBeforeClick'] -and $CheckBox.WasIndeterminateBeforeClick) {
|
||||
# WPF toggles null -> false before Click handlers fire; restore desired mixed -> checked behavior.
|
||||
$CheckBox.WasIndeterminateBeforeClick = $false
|
||||
$CheckBox.IsChecked = $true
|
||||
return $true
|
||||
}
|
||||
|
||||
return ($CheckBox.IsChecked -eq $true)
|
||||
}
|
||||
|
||||
function Set-TriStatePresetCheckBoxState {
|
||||
param(
|
||||
[System.Windows.Controls.CheckBox]$CheckBox,
|
||||
[int]$Total,
|
||||
[int]$Selected
|
||||
)
|
||||
|
||||
if (-not $CheckBox) { return }
|
||||
|
||||
if ($Total -eq 0) {
|
||||
$CheckBox.IsEnabled = $false
|
||||
$CheckBox.IsChecked = $false
|
||||
return
|
||||
}
|
||||
|
||||
$CheckBox.IsEnabled = $true
|
||||
if ($Selected -eq 0) {
|
||||
$CheckBox.IsChecked = $false
|
||||
}
|
||||
elseif ($Selected -eq $Total) {
|
||||
$CheckBox.IsChecked = $true
|
||||
}
|
||||
else {
|
||||
$CheckBox.IsChecked = [System.Nullable[bool]]$null
|
||||
}
|
||||
}
|
||||
|
||||
function Update-SortArrows {
|
||||
param(
|
||||
[System.Windows.Controls.TextBlock]$SortArrowName,
|
||||
[System.Windows.Controls.TextBlock]$SortArrowDescription,
|
||||
[System.Windows.Controls.TextBlock]$SortArrowAppId
|
||||
)
|
||||
|
||||
$ease = New-Object System.Windows.Media.Animation.CubicEase
|
||||
$ease.EasingMode = 'EaseOut'
|
||||
$arrows = @{
|
||||
'Name' = $SortArrowName
|
||||
'Description' = $SortArrowDescription
|
||||
'AppId' = $SortArrowAppId
|
||||
}
|
||||
foreach ($col in $arrows.Keys) {
|
||||
$tb = $arrows[$col]
|
||||
# Active column: full opacity, rotate to indicate direction (0 = up/asc, 180 = down/desc)
|
||||
# Inactive columns: dim, reset to 0
|
||||
if ($col -eq $script:SortColumn) {
|
||||
$targetAngle = if ($script:SortAscending) { 0 } else { 180 }
|
||||
$tb.Opacity = 1.0
|
||||
}
|
||||
else {
|
||||
$targetAngle = 0
|
||||
$tb.Opacity = 0.3
|
||||
}
|
||||
$anim = New-Object System.Windows.Media.Animation.DoubleAnimation
|
||||
$anim.To = $targetAngle
|
||||
$anim.Duration = [System.Windows.Duration]::new([System.TimeSpan]::FromMilliseconds(200))
|
||||
$anim.EasingFunction = $ease
|
||||
$tb.RenderTransform.BeginAnimation([System.Windows.Media.RotateTransform]::AngleProperty, $anim)
|
||||
}
|
||||
}
|
||||
|
||||
function Update-AppsPanelRebuildSearchIndex {
|
||||
param(
|
||||
[System.Windows.Controls.Panel]$AppsPanel,
|
||||
$ActiveMatch = $null
|
||||
)
|
||||
|
||||
$newMatches = @()
|
||||
$newActiveIndex = -1
|
||||
$i = 0
|
||||
foreach ($child in $AppsPanel.Children) {
|
||||
if ($child -is [System.Windows.Controls.CheckBox] -and $child.Background -ne [System.Windows.Media.Brushes]::Transparent) {
|
||||
$newMatches += $child
|
||||
if ($null -ne $ActiveMatch -and [System.Object]::ReferenceEquals($child, $ActiveMatch)) {
|
||||
$newActiveIndex = $i
|
||||
}
|
||||
$i++
|
||||
}
|
||||
}
|
||||
$script:AppSearchMatches = $newMatches
|
||||
$script:AppSearchMatchIndex = if ($newActiveIndex -ge 0) { $newActiveIndex } elseif ($newMatches.Count -gt 0) { 0 } else { -1 }
|
||||
}
|
||||
|
||||
function Update-AppsPanelSort {
|
||||
param(
|
||||
[System.Windows.Controls.Panel]$AppsPanel,
|
||||
[System.Windows.Controls.TextBlock]$SortArrowName,
|
||||
[System.Windows.Controls.TextBlock]$SortArrowDescription,
|
||||
[System.Windows.Controls.TextBlock]$SortArrowAppId
|
||||
)
|
||||
|
||||
$children = @($AppsPanel.Children)
|
||||
$key = switch ($script:SortColumn) {
|
||||
'Name' { { $_.AppName } }
|
||||
'Description' { { $_.AppDescription } }
|
||||
'AppId' { { $_.AppIdDisplay } }
|
||||
}
|
||||
$sorted = $children | Sort-Object $key -Descending:(-not $script:SortAscending)
|
||||
$AppsPanel.Children.Clear()
|
||||
foreach ($checkbox in $sorted) {
|
||||
$AppsPanel.Children.Add($checkbox) | Out-Null
|
||||
}
|
||||
Update-SortArrows -SortArrowName $SortArrowName -SortArrowDescription $SortArrowDescription -SortArrowAppId $SortArrowAppId
|
||||
|
||||
# Rebuild search match list in new sorted order so keyboard navigation stays correct
|
||||
if ($script:AppSearchMatches.Count -gt 0) {
|
||||
$activeMatch = if ($script:AppSearchMatchIndex -ge 0 -and $script:AppSearchMatchIndex -lt $script:AppSearchMatches.Count) {
|
||||
$script:AppSearchMatches[$script:AppSearchMatchIndex]
|
||||
}
|
||||
else { $null }
|
||||
Update-AppsPanelRebuildSearchIndex -AppsPanel $AppsPanel -ActiveMatch $activeMatch
|
||||
}
|
||||
}
|
||||
|
||||
function Update-AppSelectionStatus {
|
||||
param(
|
||||
[System.Windows.Controls.Panel]$AppsPanel,
|
||||
[System.Windows.Controls.TextBlock]$AppSelectionStatus,
|
||||
[System.Windows.Controls.ComboBox]$AppRemovalScopeCombo,
|
||||
[System.Windows.Controls.Border]$AppRemovalScopeSection,
|
||||
[System.Windows.Controls.TextBlock]$AppRemovalScopeDescription,
|
||||
[System.Windows.Controls.ComboBox]$UserSelectionCombo
|
||||
)
|
||||
|
||||
$selectedCount = 0
|
||||
foreach ($child in $AppsPanel.Children) {
|
||||
if ($child -is [System.Windows.Controls.CheckBox] -and $child.IsChecked) {
|
||||
$selectedCount++
|
||||
}
|
||||
}
|
||||
$AppSelectionStatus.Text = "$selectedCount app(s) selected for removal"
|
||||
|
||||
if ($AppRemovalScopeCombo -and $AppRemovalScopeSection -and $AppRemovalScopeDescription) {
|
||||
if ($selectedCount -gt 0) {
|
||||
$AppRemovalScopeSection.Visibility = 'Visible'
|
||||
if ($UserSelectionCombo.SelectedIndex -ne 2) {
|
||||
$AppRemovalScopeCombo.IsEnabled = $true
|
||||
}
|
||||
Update-AppRemovalScopeDescription -AppRemovalScopeCombo $AppRemovalScopeCombo -AppRemovalScopeDescription $AppRemovalScopeDescription
|
||||
}
|
||||
else {
|
||||
$AppRemovalScopeSection.Visibility = 'Collapsed'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Update-AppRemovalScopeDescription {
|
||||
param(
|
||||
[System.Windows.Controls.ComboBox]$AppRemovalScopeCombo,
|
||||
[System.Windows.Controls.TextBlock]$AppRemovalScopeDescription
|
||||
)
|
||||
|
||||
$selectedItem = $AppRemovalScopeCombo.SelectedItem
|
||||
if ($selectedItem) {
|
||||
switch ($selectedItem.Content) {
|
||||
"All users" {
|
||||
$AppRemovalScopeDescription.Text = "Apps will be removed for all users and from the Windows image to prevent reinstallation for new users."
|
||||
}
|
||||
"Current user only" {
|
||||
$AppRemovalScopeDescription.Text = "Apps will only be removed for the current user. Existing and new users will not be affected."
|
||||
}
|
||||
"Target user only" {
|
||||
$AppRemovalScopeDescription.Text = "Apps will only be removed for the specified target user. Existing and new users will not be affected."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-AppPreset {
|
||||
param(
|
||||
[System.Windows.Controls.Panel]$AppsPanel,
|
||||
[scriptblock]$MatchFilter,
|
||||
[bool]$Check,
|
||||
[switch]$Exclusive
|
||||
)
|
||||
|
||||
foreach ($child in $AppsPanel.Children) {
|
||||
if ($child -is [System.Windows.Controls.CheckBox]) {
|
||||
if ($Exclusive) {
|
||||
$child.IsChecked = (& $MatchFilter $child)
|
||||
}
|
||||
elseif (& $MatchFilter $child) {
|
||||
$child.IsChecked = $Check
|
||||
}
|
||||
}
|
||||
}
|
||||
Update-AppPresetStates -AppsPanel $AppsPanel
|
||||
}
|
||||
|
||||
function Update-AppPresetStates {
|
||||
param([System.Windows.Controls.Panel]$AppsPanel)
|
||||
|
||||
$script:UpdatingPresets = $true
|
||||
try {
|
||||
# Helper: count matching and checked apps, set checkbox state
|
||||
function SetPresetState($CheckBox, [scriptblock]$MatchFilter) {
|
||||
$total = 0; $checked = 0
|
||||
foreach ($child in $AppsPanel.Children) {
|
||||
if ($child -is [System.Windows.Controls.CheckBox]) {
|
||||
if (& $MatchFilter $child) {
|
||||
$total++
|
||||
if ($child.IsChecked) { $checked++ }
|
||||
}
|
||||
}
|
||||
}
|
||||
Set-TriStatePresetCheckBoxState -CheckBox $CheckBox -Total $total -Selected $checked
|
||||
}
|
||||
|
||||
# Find preset checkboxes via window
|
||||
$window = $script:MainWindow
|
||||
$presetDefaultApps = $window.FindName('PresetDefaultApps')
|
||||
$presetLastUsed = $window.FindName('PresetLastUsed')
|
||||
|
||||
SetPresetState $presetDefaultApps { param($c) $c.SelectedByDefault -eq $true }
|
||||
foreach ($jsonCb in $script:JsonPresetCheckboxes) {
|
||||
$localIds = $jsonCb.PresetAppIds
|
||||
SetPresetState $jsonCb { param($c) (@($c.AppIds) | Where-Object { $localIds -contains $_ }).Count -gt 0 }.GetNewClosure()
|
||||
}
|
||||
|
||||
# Last used preset: only update if it's visible (has saved apps)
|
||||
if ($presetLastUsed.Visibility -ne 'Collapsed' -and $script:SavedAppIds) {
|
||||
SetPresetState $presetLastUsed { param($c) (@($c.AppIds) | Where-Object { $script:SavedAppIds -contains $_ }).Count -gt 0 }
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$script:UpdatingPresets = $false
|
||||
}
|
||||
}
|
||||
|
||||
function Scroll-ToItemIfNotVisible {
|
||||
param (
|
||||
[System.Windows.Controls.ScrollViewer]$ScrollViewer,
|
||||
[System.Windows.UIElement]$Item,
|
||||
[System.Windows.UIElement]$Container
|
||||
)
|
||||
|
||||
if (-not $ScrollViewer -or -not $Item -or -not $Container) { return }
|
||||
|
||||
try {
|
||||
$itemPosition = $Item.TransformToAncestor($Container).Transform([System.Windows.Point]::new(0, 0)).Y
|
||||
$viewportHeight = $ScrollViewer.ViewportHeight
|
||||
$itemHeight = $Item.ActualHeight
|
||||
$currentOffset = $ScrollViewer.VerticalOffset
|
||||
|
||||
# Check if the item is currently visible in the viewport
|
||||
$itemTop = $itemPosition - $currentOffset
|
||||
$itemBottom = $itemTop + $itemHeight
|
||||
|
||||
$isVisible = ($itemTop -ge 0) -and ($itemBottom -le $viewportHeight)
|
||||
|
||||
# Only scroll if the item is not visible
|
||||
if (-not $isVisible) {
|
||||
# Center the item in the viewport
|
||||
$targetOffset = $itemPosition - ($viewportHeight / 2) + ($itemHeight / 2)
|
||||
$ScrollViewer.ScrollToVerticalOffset([Math]::Max(0, $targetOffset))
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Fallback to simple bring into view
|
||||
$Item.BringIntoView()
|
||||
}
|
||||
}
|
||||
|
||||
function Find-ParentScrollViewer {
|
||||
param ([System.Windows.UIElement]$Element)
|
||||
|
||||
$parent = [System.Windows.Media.VisualTreeHelper]::GetParent($Element)
|
||||
while ($null -ne $parent) {
|
||||
if ($parent -is [System.Windows.Controls.ScrollViewer]) {
|
||||
return $parent
|
||||
}
|
||||
$parent = [System.Windows.Media.VisualTreeHelper]::GetParent($parent)
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Load-AppsWithList {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.Panel]$AppsPanel,
|
||||
[System.Windows.Controls.CheckBox]$OnlyInstalledAppsBox,
|
||||
[System.Windows.Controls.Border]$LoadingAppsIndicator,
|
||||
[System.Windows.Controls.MenuItem]$ImportConfigBtn,
|
||||
[string]$ListOfApps
|
||||
)
|
||||
|
||||
$script:MainWindowLastSelectedCheckbox = $null
|
||||
|
||||
$loaderScriptPath = $script:LoadAppsDetailsScriptPath
|
||||
$appsFilePath = $script:AppsListFilePath
|
||||
$onlyInstalled = [bool]$OnlyInstalledAppsBox.IsChecked
|
||||
|
||||
# Use preloaded data if available; otherwise load in background job
|
||||
if (-not $onlyInstalled -and $script:PreloadedAppData) {
|
||||
$rawAppData = $script:PreloadedAppData
|
||||
$script:PreloadedAppData = $null
|
||||
}
|
||||
else {
|
||||
# Load apps details in a background job to keep the UI responsive
|
||||
$rawAppData = Invoke-NonBlocking -ScriptBlock {
|
||||
param($loaderScript, $appsListFilePath, $installedList, $onlyInstalled)
|
||||
$script:AppsListFilePath = $appsListFilePath
|
||||
. $loaderScript
|
||||
LoadAppsDetailsFromJson -OnlyInstalled:$onlyInstalled -InstalledList $installedList -InitialCheckedFromJson:$false
|
||||
} -ArgumentList $loaderScriptPath, $appsFilePath, $ListOfApps, $onlyInstalled
|
||||
}
|
||||
|
||||
$appsToAdd = @($rawAppData | Where-Object { $_ -and ($_.AppId -or $_.FriendlyName) } | Sort-Object -Property FriendlyName)
|
||||
|
||||
$LoadingAppsIndicator.Visibility = 'Collapsed'
|
||||
|
||||
if ($appsToAdd.Count -eq 0) {
|
||||
$OnlyInstalledAppsBox.IsHitTestVisible = $true
|
||||
$Window.FindName('DeploymentApplyBtn').IsEnabled = $true
|
||||
if ($ImportConfigBtn) {
|
||||
$ImportConfigBtn.IsEnabled = $true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
$brushSafe = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#4CAF50')
|
||||
$brushUnsafe = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#F44336')
|
||||
$brushDefault = [System.Windows.Media.BrushConverter]::new().ConvertFromString('#FFC107')
|
||||
$brushSafe.Freeze(); $brushUnsafe.Freeze(); $brushDefault.Freeze()
|
||||
|
||||
# Create WPF controls; pump the Dispatcher every batch so the spinner keeps animating.
|
||||
$batchSize = 20
|
||||
for ($i = 0; $i -lt $appsToAdd.Count; $i++) {
|
||||
$app = $appsToAdd[$i]
|
||||
|
||||
$checkbox = New-Object System.Windows.Controls.CheckBox
|
||||
$automationName = if ($app.FriendlyName) { $app.FriendlyName } elseif ($app.AppIdDisplay) { $app.AppIdDisplay } else { $null }
|
||||
if ($automationName) { $checkbox.SetValue([System.Windows.Automation.AutomationProperties]::NameProperty, $automationName) }
|
||||
$checkbox.Tag = $app.AppIdDisplay
|
||||
$checkbox.IsChecked = $app.IsChecked
|
||||
$checkbox.Style = $Window.Resources['AppsPanelCheckBoxStyle']
|
||||
|
||||
# Build table row: Recommendation dot | Name | Description | App ID
|
||||
$row = New-Object System.Windows.Controls.Grid
|
||||
$row.Style = $Window.Resources['AppTableRowStyle']
|
||||
$c0 = New-Object System.Windows.Controls.ColumnDefinition; $c0.Width = $Window.Resources['AppTableDotColWidth']
|
||||
$c1 = New-Object System.Windows.Controls.ColumnDefinition; $c1.Width = $Window.Resources['AppTableNameColWidth']
|
||||
$c2 = New-Object System.Windows.Controls.ColumnDefinition; $c2.Width = $Window.Resources['AppTableDescColWidth']
|
||||
$c3 = New-Object System.Windows.Controls.ColumnDefinition; $c3.Width = $Window.Resources['AppTableIdColWidth']
|
||||
$row.ColumnDefinitions.Add($c0); $row.ColumnDefinitions.Add($c1)
|
||||
$row.ColumnDefinitions.Add($c2); $row.ColumnDefinitions.Add($c3)
|
||||
|
||||
$dot = New-Object System.Windows.Shapes.Ellipse
|
||||
$dot.Style = $Window.Resources['AppRecommendationDotStyle']
|
||||
$dot.Fill = switch ($app.Recommendation) { 'safe' { $brushSafe } 'unsafe' { $brushUnsafe } default { $brushDefault } }
|
||||
$dot.ToolTip = switch ($app.Recommendation) {
|
||||
'safe' { '[Recommended] Safe to remove for most users' }
|
||||
'unsafe' { '[Not Recommended] Only remove if you know what you are doing' }
|
||||
default { "[Optional] Remove if you don't need this app" }
|
||||
}
|
||||
[System.Windows.Controls.Grid]::SetColumn($dot, 0)
|
||||
|
||||
$tbName = New-Object System.Windows.Controls.TextBlock
|
||||
$tbName.Text = $app.FriendlyName
|
||||
$tbName.Style = $Window.Resources['AppNameTextStyle']
|
||||
[System.Windows.Controls.Grid]::SetColumn($tbName, 1)
|
||||
|
||||
$tbDesc = New-Object System.Windows.Controls.TextBlock
|
||||
$tbDesc.Text = $app.Description
|
||||
$tbDesc.Style = $Window.Resources['AppDescTextStyle']
|
||||
$tbDesc.ToolTip = $app.Description
|
||||
[System.Windows.Controls.Grid]::SetColumn($tbDesc, 2)
|
||||
|
||||
$tbId = New-Object System.Windows.Controls.TextBlock
|
||||
$tbId.Text = $app.AppIdDisplay
|
||||
$tbId.Style = $Window.Resources["AppIdTextStyle"]
|
||||
$tbId.ToolTip = $app.AppIdDisplay
|
||||
[System.Windows.Controls.Grid]::SetColumn($tbId, 3)
|
||||
|
||||
$row.Children.Add($dot) | Out-Null
|
||||
$row.Children.Add($tbName) | Out-Null
|
||||
$row.Children.Add($tbDesc) | Out-Null
|
||||
$row.Children.Add($tbId) | Out-Null
|
||||
$checkbox.Content = $row
|
||||
|
||||
Add-Member -InputObject $checkbox -MemberType NoteProperty -Name 'AppName' -Value $app.FriendlyName
|
||||
Add-Member -InputObject $checkbox -MemberType NoteProperty -Name 'AppDescription' -Value $app.Description
|
||||
Add-Member -InputObject $checkbox -MemberType NoteProperty -Name 'SelectedByDefault' -Value $app.SelectedByDefault
|
||||
Add-Member -InputObject $checkbox -MemberType NoteProperty -Name 'AppIds' -Value @($app.AppId)
|
||||
Add-Member -InputObject $checkbox -MemberType NoteProperty -Name 'AppIdDisplay' -Value $app.AppIdDisplay
|
||||
|
||||
$checkbox.Add_Checked({
|
||||
$w = $script:MainWindow
|
||||
Update-AppSelectionStatus -AppsPanel $w.FindName('AppSelectionPanel') `
|
||||
-AppSelectionStatus $w.FindName('AppSelectionStatus') `
|
||||
-AppRemovalScopeCombo $w.FindName('AppRemovalScopeCombo') `
|
||||
-AppRemovalScopeSection $w.FindName('AppRemovalScopeSection') `
|
||||
-AppRemovalScopeDescription $w.FindName('AppRemovalScopeDescription') `
|
||||
-UserSelectionCombo $w.FindName('UserSelectionCombo')
|
||||
})
|
||||
$checkbox.Add_Unchecked({
|
||||
$w = $script:MainWindow
|
||||
Update-AppSelectionStatus -AppsPanel $w.FindName('AppSelectionPanel') `
|
||||
-AppSelectionStatus $w.FindName('AppSelectionStatus') `
|
||||
-AppRemovalScopeCombo $w.FindName('AppRemovalScopeCombo') `
|
||||
-AppRemovalScopeSection $w.FindName('AppRemovalScopeSection') `
|
||||
-AppRemovalScopeDescription $w.FindName('AppRemovalScopeDescription') `
|
||||
-UserSelectionCombo $w.FindName('UserSelectionCombo')
|
||||
})
|
||||
AttachShiftClickBehavior -checkbox $checkbox -appsPanel $AppsPanel `
|
||||
-lastSelectedCheckboxRef ([ref]$script:MainWindowLastSelectedCheckbox) `
|
||||
-updateStatusCallback {
|
||||
$w = $script:MainWindow
|
||||
Update-AppSelectionStatus -AppsPanel $w.FindName('AppSelectionPanel') `
|
||||
-AppSelectionStatus $w.FindName('AppSelectionStatus') `
|
||||
-AppRemovalScopeCombo $w.FindName('AppRemovalScopeCombo') `
|
||||
-AppRemovalScopeSection $w.FindName('AppRemovalScopeSection') `
|
||||
-AppRemovalScopeDescription $w.FindName('AppRemovalScopeDescription') `
|
||||
-UserSelectionCombo $w.FindName('UserSelectionCombo')
|
||||
}
|
||||
|
||||
$AppsPanel.Children.Add($checkbox) | Out-Null
|
||||
|
||||
if (($i + 1) % $batchSize -eq 0) { DoEvents }
|
||||
}
|
||||
|
||||
$sortArrowName = $Window.FindName('SortArrowName')
|
||||
$sortArrowDescription = $Window.FindName('SortArrowDescription')
|
||||
$sortArrowAppId = $Window.FindName('SortArrowAppId')
|
||||
Update-AppsPanelSort -AppsPanel $AppsPanel -SortArrowName $sortArrowName -SortArrowDescription $sortArrowDescription -SortArrowAppId $sortArrowAppId
|
||||
|
||||
# If Default Mode was clicked while apps were still loading, apply defaults now
|
||||
if ($script:PendingDefaultMode) {
|
||||
$script:PendingDefaultMode = $false
|
||||
Invoke-AppPreset -AppsPanel $AppsPanel -MatchFilter { param($c) $c.SelectedByDefault -eq $true } -Exclusive
|
||||
}
|
||||
|
||||
$appSelectionStatusText = $Window.FindName('AppSelectionStatus')
|
||||
$appRemovalScopeCombo = $Window.FindName('AppRemovalScopeCombo')
|
||||
$appRemovalScopeSection = $Window.FindName('AppRemovalScopeSection')
|
||||
$appRemovalScopeDescription = $Window.FindName('AppRemovalScopeDescription')
|
||||
$userSelectionCombo = $Window.FindName('UserSelectionCombo')
|
||||
Update-AppSelectionStatus -AppsPanel $AppsPanel -AppSelectionStatus $appSelectionStatusText `
|
||||
-AppRemovalScopeCombo $appRemovalScopeCombo -AppRemovalScopeSection $appRemovalScopeSection `
|
||||
-AppRemovalScopeDescription $appRemovalScopeDescription -UserSelectionCombo $userSelectionCombo
|
||||
|
||||
# Re-enable controls now that the full, correctly-checked app list is ready
|
||||
$OnlyInstalledAppsBox.IsHitTestVisible = $true
|
||||
$Window.FindName('DeploymentApplyBtn').IsEnabled = $true
|
||||
if ($ImportConfigBtn) {
|
||||
$ImportConfigBtn.IsEnabled = $true
|
||||
}
|
||||
}
|
||||
|
||||
function Load-AppsIntoMainUI {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.Panel]$AppsPanel,
|
||||
[System.Windows.Controls.CheckBox]$OnlyInstalledAppsBox,
|
||||
[System.Windows.Controls.Border]$LoadingAppsIndicator,
|
||||
[System.Windows.Controls.MenuItem]$ImportConfigBtn
|
||||
)
|
||||
|
||||
# Prevent concurrent loads
|
||||
if ($script:IsLoadingApps) { return }
|
||||
$script:IsLoadingApps = $true
|
||||
|
||||
if ($ImportConfigBtn) {
|
||||
$ImportConfigBtn.IsEnabled = $false
|
||||
}
|
||||
|
||||
# Show loading indicator and clear existing apps
|
||||
$LoadingAppsIndicator.Visibility = 'Visible'
|
||||
$AppsPanel.Children.Clear()
|
||||
|
||||
# Disable controls while apps are loading so they can't be interacted with mid-load
|
||||
$Window.FindName('DeploymentApplyBtn').IsEnabled = $false
|
||||
$OnlyInstalledAppsBox.IsHitTestVisible = $false
|
||||
|
||||
# Update navigation buttons to disable Next/Previous
|
||||
Update-NavigationButtons -Window $Window -TabControl $Window.FindName('MainTabControl')
|
||||
|
||||
# Force a render so the loading indicator is visible, then schedule the
|
||||
# actual loading at Background priority so this call returns immediately.
|
||||
# This is critical when called from Add_Loaded: the window must finish
|
||||
# its initialization before we start a nested message pump via DoEvents.
|
||||
$Window.Dispatcher.Invoke([System.Windows.Threading.DispatcherPriority]::Render, [action] {})
|
||||
$Window.Dispatcher.BeginInvoke([System.Windows.Threading.DispatcherPriority]::Background, [action] {
|
||||
try {
|
||||
$listOfApps = ""
|
||||
|
||||
if ($OnlyInstalledAppsBox.IsChecked -and ($script:WingetInstalled -eq $true)) {
|
||||
$listOfApps = GetInstalledAppsViaWinget -TimeOut 10 -NonBlocking
|
||||
|
||||
if ($null -eq $listOfApps) {
|
||||
Show-MessageBox -Message 'Unable to load list of installed apps via WinGet.' -Title 'Error' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
$OnlyInstalledAppsBox.IsChecked = $false
|
||||
}
|
||||
}
|
||||
|
||||
Load-AppsWithList -Window $Window -AppsPanel $AppsPanel -OnlyInstalledAppsBox $OnlyInstalledAppsBox `
|
||||
-LoadingAppsIndicator $LoadingAppsIndicator -ImportConfigBtn $ImportConfigBtn -ListOfApps $listOfApps
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Failed to load apps list: $($_.Exception.Message)"
|
||||
$LoadingAppsIndicator.Visibility = 'Collapsed'
|
||||
$OnlyInstalledAppsBox.IsHitTestVisible = $true
|
||||
$Window.FindName('DeploymentApplyBtn').IsEnabled = $true
|
||||
if ($ImportConfigBtn) { $ImportConfigBtn.IsEnabled = $true }
|
||||
}
|
||||
finally {
|
||||
$script:IsLoadingApps = $false
|
||||
}
|
||||
}) | Out-Null
|
||||
}
|
||||
487
Scripts/GUI/MainWindow-Deployment.ps1
Normal file
487
Scripts/GUI/MainWindow-Deployment.ps1
Normal file
@@ -0,0 +1,487 @@
|
||||
# MainWindow-Deployment.ps1
|
||||
# Overview generation, pending tweak actions, feature labels, tweak preset maps, apply logic, user mode state, user selection, and validation.
|
||||
|
||||
function Get-FeatureLabel {
|
||||
param(
|
||||
[string]$FeatureId,
|
||||
$FallbackLabel = $null
|
||||
)
|
||||
|
||||
$label = $script:FeatureLabelLookup[$FeatureId]
|
||||
if (-not [string]::IsNullOrWhiteSpace([string]$label)) {
|
||||
return [string]$label
|
||||
}
|
||||
|
||||
if (-not [string]::IsNullOrWhiteSpace([string]$FallbackLabel)) {
|
||||
return [string]$FallbackLabel
|
||||
}
|
||||
|
||||
return [string]$FeatureId
|
||||
}
|
||||
|
||||
function Get-UndoFeatureLabel {
|
||||
param(
|
||||
[string]$FeatureId,
|
||||
$FallbackLabel = $null
|
||||
)
|
||||
|
||||
$undoLabel = $script:UndoFeatureLabelLookup[$FeatureId]
|
||||
if (-not [string]::IsNullOrWhiteSpace([string]$undoLabel)) {
|
||||
return [string]$undoLabel
|
||||
}
|
||||
|
||||
# Fall back to the regular label (prefixed for undo context)
|
||||
$label = Get-FeatureLabel -FeatureId $FeatureId -FallbackLabel $FallbackLabel
|
||||
return [string]$label
|
||||
}
|
||||
|
||||
function Get-PendingTweakActions {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[bool]$ShowAppliedTweaksMode
|
||||
)
|
||||
|
||||
$actions = New-Object System.Collections.Generic.List[object]
|
||||
|
||||
if (-not $script:UiControlMappings) {
|
||||
return @($actions.ToArray())
|
||||
}
|
||||
|
||||
foreach ($mappingKey in $script:UiControlMappings.Keys) {
|
||||
$control = $Window.FindName($mappingKey)
|
||||
if (-not $control) { continue }
|
||||
$mapping = $script:UiControlMappings[$mappingKey]
|
||||
|
||||
if ($control -is [System.Windows.Controls.CheckBox] -and $mapping.Type -eq 'feature') {
|
||||
$wasApplied = $false
|
||||
if ($ShowAppliedTweaksMode -and $null -ne $control.PSObject.Properties['SystemState']) {
|
||||
$wasApplied = [bool]$control.SystemState
|
||||
}
|
||||
elseif ($null -ne $control.PSObject.Properties['InitialState']) {
|
||||
$wasApplied = [bool]$control.InitialState
|
||||
}
|
||||
elseif ($null -ne $control.PSObject.Properties['SystemState']) {
|
||||
$wasApplied = [bool]$control.SystemState
|
||||
}
|
||||
$isNowChecked = $control.IsChecked -eq $true
|
||||
|
||||
if (-not $wasApplied -and $isNowChecked) {
|
||||
$actions.Add([PSCustomObject]@{
|
||||
Action = 'Apply'
|
||||
FeatureId = [string]$mapping.FeatureId
|
||||
Label = (Get-FeatureLabel -FeatureId $mapping.FeatureId -FallbackLabel $mapping.Label)
|
||||
})
|
||||
}
|
||||
elseif ($wasApplied -and -not $isNowChecked) {
|
||||
$actions.Add([PSCustomObject]@{
|
||||
Action = 'Undo'
|
||||
FeatureId = [string]$mapping.FeatureId
|
||||
Label = (Get-FeatureLabel -FeatureId $mapping.FeatureId -FallbackLabel $mapping.Label)
|
||||
})
|
||||
}
|
||||
}
|
||||
elseif ($control -is [System.Windows.Controls.ComboBox] -and $mapping.Type -eq 'group') {
|
||||
$wasIndex = 0
|
||||
if ($ShowAppliedTweaksMode -and $null -ne $control.PSObject.Properties['SystemIndex']) {
|
||||
$wasIndex = [int]$control.SystemIndex
|
||||
}
|
||||
elseif ($null -ne $control.PSObject.Properties['InitialIndex']) {
|
||||
$wasIndex = [int]$control.InitialIndex
|
||||
}
|
||||
elseif ($null -ne $control.PSObject.Properties['SystemIndex']) {
|
||||
$wasIndex = [int]$control.SystemIndex
|
||||
}
|
||||
$isNowIndex = $control.SelectedIndex
|
||||
|
||||
if ($wasIndex -eq $isNowIndex) { continue }
|
||||
|
||||
if ($isNowIndex -gt 0 -and $isNowIndex -le $mapping.Values.Count) {
|
||||
$selectedValue = $mapping.Values[$isNowIndex - 1]
|
||||
foreach ($fid in $selectedValue.FeatureIds) {
|
||||
$actions.Add([PSCustomObject]@{
|
||||
Action = 'Apply'
|
||||
FeatureId = [string]$fid
|
||||
Label = (Get-FeatureLabel -FeatureId $fid)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return @($actions.ToArray())
|
||||
}
|
||||
|
||||
function New-Overview {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.StackPanel]$AppsPanel,
|
||||
$ShowCurrentlyAppliedTweaksCheckBox
|
||||
)
|
||||
|
||||
$changesList = @()
|
||||
$showAppliedTweaksMode = ($ShowCurrentlyAppliedTweaksCheckBox -and $ShowCurrentlyAppliedTweaksCheckBox.IsChecked -eq $true)
|
||||
|
||||
# Collect selected apps
|
||||
$selectedAppsCount = 0
|
||||
foreach ($child in $AppsPanel.Children) {
|
||||
if ($child -is [System.Windows.Controls.CheckBox] -and $child.IsChecked) {
|
||||
$selectedAppsCount++
|
||||
}
|
||||
}
|
||||
if ($selectedAppsCount -gt 0) {
|
||||
$changesList += "Remove $selectedAppsCount application(s)"
|
||||
}
|
||||
|
||||
foreach ($tweakAction in @(Get-PendingTweakActions -Window $Window -ShowAppliedTweaksMode:$showAppliedTweaksMode)) {
|
||||
if ($tweakAction.Action -eq 'Undo') {
|
||||
$changesList += "Undo: $($tweakAction.Label)"
|
||||
}
|
||||
else {
|
||||
$changesList += $tweakAction.Label
|
||||
}
|
||||
}
|
||||
|
||||
return $changesList
|
||||
}
|
||||
|
||||
function Invoke-ShowChangesOverview {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.StackPanel]$AppsPanel,
|
||||
$ShowCurrentlyAppliedTweaksCheckBox
|
||||
)
|
||||
|
||||
$changesList = New-Overview -Window $Window -AppsPanel $AppsPanel -ShowCurrentlyAppliedTweaksCheckBox $ShowCurrentlyAppliedTweaksCheckBox
|
||||
|
||||
if ($changesList.Count -eq 0) {
|
||||
Show-MessageBox -Message 'No changes have been selected.' -Title 'Selected Changes' -Button 'OK' -Icon 'Information'
|
||||
return
|
||||
}
|
||||
|
||||
$message = ($changesList | ForEach-Object { "$([char]0x2022) $_" }) -join "`n"
|
||||
Show-MessageBox -Message $message -Title 'Selected Changes' -Button 'OK' -Icon 'None' -Width 600
|
||||
}
|
||||
|
||||
function Build-TweakPresetControlMap {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
$SettingsJson
|
||||
)
|
||||
|
||||
$presetMap = @{}
|
||||
if (-not $SettingsJson -or -not $SettingsJson.Settings -or -not $script:UiControlMappings) {
|
||||
return $presetMap
|
||||
}
|
||||
|
||||
# FeatureId -> control metadata, similar to ApplySettingsToUiControls lookup.
|
||||
$featureIdIndex = @{}
|
||||
foreach ($controlName in $script:UiControlMappings.Keys) {
|
||||
$control = $Window.FindName($controlName)
|
||||
if (-not $control -or $control.Visibility -ne 'Visible') { continue }
|
||||
|
||||
$mapping = $script:UiControlMappings[$controlName]
|
||||
if ($mapping.Type -eq 'group') {
|
||||
$i = 1
|
||||
foreach ($val in $mapping.Values) {
|
||||
foreach ($fid in $val.FeatureIds) {
|
||||
$featureIdIndex[$fid] = @{ ControlName = $controlName; Control = $control; MappingType = 'group'; Index = $i }
|
||||
}
|
||||
$i++
|
||||
}
|
||||
}
|
||||
elseif ($mapping.Type -eq 'feature') {
|
||||
$featureIdIndex[$mapping.FeatureId] = @{ ControlName = $controlName; Control = $control; MappingType = 'feature' }
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($setting in $SettingsJson.Settings) {
|
||||
if ($setting.Value -ne $true) { continue }
|
||||
if ($setting.Name -eq 'CreateRestorePoint') { continue }
|
||||
|
||||
$entry = $featureIdIndex[$setting.Name]
|
||||
if (-not $entry) { continue }
|
||||
if ($presetMap.ContainsKey($entry.ControlName)) { continue }
|
||||
|
||||
$controlType = if ($entry.Control -is [System.Windows.Controls.CheckBox]) { 'CheckBox' } else { 'ComboBox' }
|
||||
$desiredValue = switch ($entry.MappingType) {
|
||||
'group' { $entry.Index }
|
||||
default { if ($controlType -eq 'CheckBox') { $true } else { 1 } }
|
||||
}
|
||||
|
||||
$presetMap[$entry.ControlName] = @{ Control = $entry.Control; ControlType = $controlType; DesiredValue = $desiredValue }
|
||||
}
|
||||
|
||||
return $presetMap
|
||||
}
|
||||
|
||||
function Build-CategoryTweakPresetMap {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[string]$Category
|
||||
)
|
||||
|
||||
$presetMap = @{}
|
||||
if (-not $script:UiControlMappings) { return $presetMap }
|
||||
|
||||
foreach ($controlName in $script:UiControlMappings.Keys) {
|
||||
$mapping = $script:UiControlMappings[$controlName]
|
||||
if ($mapping.Category -ne $Category) { continue }
|
||||
|
||||
$control = $Window.FindName($controlName)
|
||||
if (-not $control -or $control.Visibility -ne 'Visible') { continue }
|
||||
|
||||
$controlType = if ($control -is [System.Windows.Controls.CheckBox]) { 'CheckBox' } else { 'ComboBox' }
|
||||
$desiredValue = if ($controlType -eq 'CheckBox') { $true } else { 1 }
|
||||
$presetMap[$controlName] = @{ Control = $control; ControlType = $controlType; DesiredValue = $desiredValue }
|
||||
}
|
||||
|
||||
return $presetMap
|
||||
}
|
||||
|
||||
function Get-SavedAppIdsFromSettingsJson {
|
||||
param($SettingsJson)
|
||||
|
||||
if (-not $SettingsJson -or -not $SettingsJson.Settings) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$appsValue = $null
|
||||
foreach ($setting in $SettingsJson.Settings) {
|
||||
if ($setting.Name -eq 'Apps' -and $setting.Value) {
|
||||
$appsValue = $setting.Value
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $appsValue) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$savedAppIds = @()
|
||||
if ($appsValue -is [string]) {
|
||||
$savedAppIds = $appsValue.Split(',')
|
||||
}
|
||||
elseif ($appsValue -is [array]) {
|
||||
$savedAppIds = $appsValue
|
||||
}
|
||||
|
||||
$savedAppIds = $savedAppIds | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
|
||||
if ($savedAppIds.Count -eq 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
return $savedAppIds
|
||||
}
|
||||
|
||||
function Invoke-ApplyTweakPresetMap {
|
||||
param(
|
||||
[hashtable]$PresetMap,
|
||||
[bool]$Check
|
||||
)
|
||||
|
||||
if (-not $PresetMap) {
|
||||
$PresetMap = @{}
|
||||
}
|
||||
|
||||
$wasUpdatingTweakPresets = [bool]$script:UpdatingTweakPresets
|
||||
$script:UpdatingTweakPresets = $true
|
||||
try {
|
||||
foreach ($target in $PresetMap.Values) {
|
||||
$control = $target.Control
|
||||
if (-not $control) { continue }
|
||||
|
||||
if ($target.ControlType -eq 'CheckBox') {
|
||||
$control.IsChecked = $Check
|
||||
}
|
||||
elseif ($target.ControlType -eq 'ComboBox') {
|
||||
$desiredIndex = [int]$target.DesiredValue
|
||||
if ($Check) {
|
||||
$control.SelectedIndex = $desiredIndex
|
||||
}
|
||||
elseif ($control.SelectedIndex -eq $desiredIndex) {
|
||||
$control.SelectedIndex = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally {
|
||||
$script:UpdatingTweakPresets = $wasUpdatingTweakPresets
|
||||
}
|
||||
|
||||
if (-not $wasUpdatingTweakPresets) {
|
||||
Update-TweakPresetStates -Window $script:MainWindow
|
||||
}
|
||||
}
|
||||
|
||||
function Set-TweakPresetCheckBoxState {
|
||||
param(
|
||||
[System.Windows.Controls.CheckBox]$PresetCheckBox,
|
||||
[hashtable]$PresetMap
|
||||
)
|
||||
|
||||
if (-not $PresetCheckBox) { return }
|
||||
if (-not $PresetMap) {
|
||||
$PresetMap = @{}
|
||||
}
|
||||
|
||||
$total = $PresetMap.Count
|
||||
$selected = 0
|
||||
|
||||
foreach ($target in $PresetMap.Values) {
|
||||
$control = $target.Control
|
||||
if (-not $control) { continue }
|
||||
|
||||
if ($target.ControlType -eq 'CheckBox' -and $control.IsChecked -eq $true) {
|
||||
$selected++
|
||||
}
|
||||
elseif ($target.ControlType -eq 'ComboBox' -and $control.SelectedIndex -eq [int]$target.DesiredValue) {
|
||||
$selected++
|
||||
}
|
||||
}
|
||||
|
||||
Set-TriStatePresetCheckBoxState -CheckBox $PresetCheckBox -Total $total -Selected $selected
|
||||
}
|
||||
|
||||
function Update-TweakPresetStates {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
$script:UpdatingTweakPresets = $true
|
||||
try {
|
||||
$presetDefaultTweaksBtn = $Window.FindName('PresetDefaultTweaksBtn')
|
||||
$presetLastUsedTweaksBtn = $Window.FindName('PresetLastUsedTweaksBtn')
|
||||
$presetPrivacyTweaksBtn = $Window.FindName('PresetPrivacyTweaksBtn')
|
||||
$presetAITweaksBtn = $Window.FindName('PresetAITweaksBtn')
|
||||
|
||||
Set-TweakPresetCheckBoxState -PresetCheckBox $presetDefaultTweaksBtn -PresetMap $script:DefaultTweakPresetMap
|
||||
if ($presetLastUsedTweaksBtn -and $presetLastUsedTweaksBtn.Visibility -ne 'Collapsed') {
|
||||
Set-TweakPresetCheckBoxState -PresetCheckBox $presetLastUsedTweaksBtn -PresetMap $script:LastUsedTweakPresetMap
|
||||
}
|
||||
Set-TweakPresetCheckBoxState -PresetCheckBox $presetPrivacyTweaksBtn -PresetMap $script:PrivacyTweakPresetMap
|
||||
Set-TweakPresetCheckBoxState -PresetCheckBox $presetAITweaksBtn -PresetMap $script:AITweakPresetMap
|
||||
}
|
||||
finally {
|
||||
$script:UpdatingTweakPresets = $false
|
||||
}
|
||||
}
|
||||
|
||||
function Register-TweakPresetControlStateHandlers {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
if (-not $script:UiControlMappings) { return }
|
||||
|
||||
foreach ($controlName in $script:UiControlMappings.Keys) {
|
||||
$control = $Window.FindName($controlName)
|
||||
if (-not $control) { continue }
|
||||
|
||||
if ($control -is [System.Windows.Controls.CheckBox]) {
|
||||
$control.Add_Checked({ if (-not $script:UpdatingTweakPresets) { Update-TweakPresetStates -Window $script:MainWindow } })
|
||||
$control.Add_Unchecked({ if (-not $script:UpdatingTweakPresets) { Update-TweakPresetStates -Window $script:MainWindow } })
|
||||
}
|
||||
elseif ($control -is [System.Windows.Controls.ComboBox]) {
|
||||
$control.Add_SelectionChanged({ if (-not $script:UpdatingTweakPresets) { Update-TweakPresetStates -Window $script:MainWindow } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Initialize-TweakPresetSources {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
$DefaultSettingsJson,
|
||||
$LastUsedSettingsJson
|
||||
)
|
||||
|
||||
$script:DefaultTweakPresetMap = Build-TweakPresetControlMap -Window $Window -SettingsJson $DefaultSettingsJson
|
||||
$script:LastUsedTweakPresetMap = Build-TweakPresetControlMap -Window $Window -SettingsJson $LastUsedSettingsJson
|
||||
$script:PrivacyTweakPresetMap = Build-CategoryTweakPresetMap -Window $Window -Category 'Privacy & Suggested Content'
|
||||
$script:AITweakPresetMap = Build-CategoryTweakPresetMap -Window $Window -Category 'AI'
|
||||
|
||||
$presetLastUsedTweaksBtn = $Window.FindName('PresetLastUsedTweaksBtn')
|
||||
if ($presetLastUsedTweaksBtn) {
|
||||
$presetLastUsedTweaksBtn.Visibility = if ($script:LastUsedTweakPresetMap.Count -gt 0) { 'Visible' } else { 'Collapsed' }
|
||||
}
|
||||
}
|
||||
|
||||
function Update-AppliedTweaksUserModeState {
|
||||
param(
|
||||
[System.Windows.Controls.CheckBox]$ShowCurrentlyAppliedTweaksCheckBox,
|
||||
[System.Windows.Controls.ComboBox]$UserSelectionCombo
|
||||
)
|
||||
|
||||
# Show/hide detect applied tweaks checkbox based on user mode
|
||||
if ($ShowCurrentlyAppliedTweaksCheckBox) {
|
||||
if ($UserSelectionCombo.SelectedIndex -eq 0) {
|
||||
$ShowCurrentlyAppliedTweaksCheckBox.Visibility = 'Visible'
|
||||
}
|
||||
else {
|
||||
$ShowCurrentlyAppliedTweaksCheckBox.Visibility = 'Collapsed'
|
||||
}
|
||||
}
|
||||
|
||||
# Enable/disable user mode combo based on params only (not checkbox)
|
||||
if ($script:Params.ContainsKey('Sysprep') -or $script:Params.ContainsKey('User')) {
|
||||
$UserSelectionCombo.IsEnabled = $false
|
||||
}
|
||||
else {
|
||||
$UserSelectionCombo.IsEnabled = $true
|
||||
}
|
||||
}
|
||||
|
||||
function Update-UserSelectionDescription {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.ComboBox]$UserSelectionCombo,
|
||||
[System.Windows.Controls.TextBox]$OtherUsernameTextBox,
|
||||
[System.Windows.Controls.TextBlock]$UserSelectionDescription
|
||||
)
|
||||
|
||||
switch ($UserSelectionCombo.SelectedIndex) {
|
||||
0 {
|
||||
$currentUserName = GetUserName
|
||||
if ([string]::IsNullOrWhiteSpace($currentUserName)) {
|
||||
$UserSelectionDescription.Text = "The currently logged-in user profile"
|
||||
}
|
||||
else {
|
||||
$UserSelectionDescription.Text = "The currently logged-in user profile: $currentUserName"
|
||||
}
|
||||
}
|
||||
1 {
|
||||
$targetUserName = $OtherUsernameTextBox.Text.Trim()
|
||||
if ([string]::IsNullOrWhiteSpace($targetUserName)) {
|
||||
$UserSelectionDescription.Text = "A different user profile on this system"
|
||||
}
|
||||
else {
|
||||
$UserSelectionDescription.Text = "A different user profile on this system: $targetUserName"
|
||||
}
|
||||
}
|
||||
default {
|
||||
$UserSelectionDescription.Text = "The default user template, affecting all new users created after this point. Useful for Sysprep deployment."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Test-OtherUsername {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.ComboBox]$UserSelectionCombo,
|
||||
[System.Windows.Controls.TextBox]$OtherUsernameTextBox,
|
||||
[System.Windows.Controls.TextBlock]$UsernameValidationMessage
|
||||
)
|
||||
|
||||
# Only validate if "Other User" is selected
|
||||
if ($UserSelectionCombo.SelectedIndex -ne 1) {
|
||||
return $true
|
||||
}
|
||||
|
||||
$errorBrush = $Window.Resources['ValidationErrorColor']
|
||||
$successBrush = $Window.Resources['ValidationSuccessColor']
|
||||
$validationResult = Test-TargetUserName -UserName $OtherUsernameTextBox.Text
|
||||
|
||||
$UsernameValidationMessage.Text = $validationResult.Message
|
||||
if ($validationResult.IsValid) {
|
||||
$UsernameValidationMessage.Foreground = $successBrush
|
||||
return $true
|
||||
}
|
||||
|
||||
$UsernameValidationMessage.Foreground = $errorBrush
|
||||
return $false
|
||||
}
|
||||
72
Scripts/GUI/MainWindow-Navigation.ps1
Normal file
72
Scripts/GUI/MainWindow-Navigation.ps1
Normal file
@@ -0,0 +1,72 @@
|
||||
# MainWindow-Navigation.ps1
|
||||
# Wizard navigation helpers: tab navigation buttons and progress indicators.
|
||||
|
||||
function Update-NavigationButtons {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.TabControl]$TabControl
|
||||
)
|
||||
|
||||
$currentIndex = $TabControl.SelectedIndex
|
||||
$totalTabs = $TabControl.Items.Count
|
||||
|
||||
$previousBtn = $Window.FindName('PreviousBtn')
|
||||
$nextBtn = $Window.FindName('NextBtn')
|
||||
|
||||
$homeIndex = 0
|
||||
$overviewIndex = $totalTabs - 1
|
||||
|
||||
# Navigation button visibility
|
||||
if ($currentIndex -eq $homeIndex) {
|
||||
$nextBtn.Visibility = 'Collapsed'
|
||||
$previousBtn.Visibility = 'Collapsed'
|
||||
}
|
||||
elseif ($currentIndex -eq $overviewIndex) {
|
||||
$nextBtn.Visibility = 'Collapsed'
|
||||
$previousBtn.Visibility = 'Visible'
|
||||
}
|
||||
else {
|
||||
$nextBtn.Visibility = 'Visible'
|
||||
$previousBtn.Visibility = 'Visible'
|
||||
}
|
||||
|
||||
# Update progress indicators
|
||||
# Tab indices: 0=Home, 1=App Removal, 2=Tweaks, 3=Deployment Settings
|
||||
$progressIndicator1 = $Window.FindName('ProgressIndicator1') # App Removal
|
||||
$progressIndicator2 = $Window.FindName('ProgressIndicator2') # Tweaks
|
||||
$progressIndicator3 = $Window.FindName('ProgressIndicator3') # Deployment Settings
|
||||
$bottomNavGrid = $Window.FindName('BottomNavGrid')
|
||||
|
||||
# Hide bottom navigation on home page
|
||||
if ($currentIndex -eq 0) {
|
||||
$bottomNavGrid.Visibility = 'Collapsed'
|
||||
}
|
||||
else {
|
||||
$bottomNavGrid.Visibility = 'Visible'
|
||||
}
|
||||
|
||||
# Update indicator colors based on current tab
|
||||
# Indicator 1 (App Removal) - tab index 1
|
||||
if ($currentIndex -ge 1) {
|
||||
$progressIndicator1.Fill = $Window.Resources['ProgressActiveColor']
|
||||
}
|
||||
else {
|
||||
$progressIndicator1.Fill = $Window.Resources['ProgressInactiveColor']
|
||||
}
|
||||
|
||||
# Indicator 2 (Tweaks) - tab index 2
|
||||
if ($currentIndex -ge 2) {
|
||||
$progressIndicator2.Fill = $Window.Resources['ProgressActiveColor']
|
||||
}
|
||||
else {
|
||||
$progressIndicator2.Fill = $Window.Resources['ProgressInactiveColor']
|
||||
}
|
||||
|
||||
# Indicator 3 (Deployment Settings) - tab index 3
|
||||
if ($currentIndex -ge 3) {
|
||||
$progressIndicator3.Fill = $Window.Resources['ProgressActiveColor']
|
||||
}
|
||||
else {
|
||||
$progressIndicator3.Fill = $Window.Resources['ProgressInactiveColor']
|
||||
}
|
||||
}
|
||||
511
Scripts/GUI/MainWindow-TweaksBuilder.ps1
Normal file
511
Scripts/GUI/MainWindow-TweaksBuilder.ps1
Normal file
@@ -0,0 +1,511 @@
|
||||
# MainWindow-TweaksBuilder.ps1
|
||||
# Dynamic tweaks UI construction from Features.json, tweak state management, selection clear, and search/highlight.
|
||||
|
||||
function Build-DynamicTweaks {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[int]$WinVersion
|
||||
)
|
||||
|
||||
$featuresJson = LoadJsonFile -filePath $script:FeaturesFilePath -expectedVersion "1.0"
|
||||
|
||||
if (-not $featuresJson) {
|
||||
throw "Unable to load Features.json file. The GUI cannot continue without feature definitions."
|
||||
}
|
||||
|
||||
# Column containers
|
||||
$col0 = $Window.FindName('Column0Panel')
|
||||
$col1 = $Window.FindName('Column1Panel')
|
||||
$col2 = $Window.FindName('Column2Panel')
|
||||
$columns = @($col0, $col1, $col2) | Where-Object { $_ -ne $null }
|
||||
|
||||
# Clear all columns for fully dynamic panel creation
|
||||
foreach ($col in $columns) {
|
||||
if ($col) { $col.Children.Clear() }
|
||||
}
|
||||
|
||||
$script:UiControlMappings = @{}
|
||||
$script:CategoryCardMap = @{}
|
||||
$script:TweaksCompactMode = $null
|
||||
$script:TweaksCardsMovedFromCol2 = @()
|
||||
|
||||
function CreateLabeledCombo($parent, $labelText, $comboName, $items) {
|
||||
# If only 2 items (No Change + one option), use a checkbox instead
|
||||
if ($items.Count -eq 2) {
|
||||
$checkbox = New-Object System.Windows.Controls.CheckBox
|
||||
$checkbox.Content = $labelText
|
||||
$checkbox.Name = $comboName
|
||||
$checkbox.SetValue([System.Windows.Automation.AutomationProperties]::NameProperty, $labelText)
|
||||
$checkbox.IsChecked = $false
|
||||
$checkbox.Style = $Window.Resources["FeatureCheckboxStyle"]
|
||||
$parent.Children.Add($checkbox) | Out-Null
|
||||
|
||||
# Register the checkbox with the window's name scope
|
||||
try {
|
||||
[System.Windows.NameScope]::SetNameScope($checkbox, [System.Windows.NameScope]::GetNameScope($Window))
|
||||
$Window.RegisterName($comboName, $checkbox)
|
||||
}
|
||||
catch {
|
||||
# Name might already be registered, ignore
|
||||
}
|
||||
|
||||
return $checkbox
|
||||
}
|
||||
|
||||
# Otherwise use a combobox for multiple options
|
||||
# Wrap label in a Border for search highlighting
|
||||
$lblBorder = New-Object System.Windows.Controls.Border
|
||||
$lblBorder.Style = $Window.Resources['LabelBorderStyle']
|
||||
$lblBorderName = "$comboName`_LabelBorder"
|
||||
$lblBorder.Name = $lblBorderName
|
||||
|
||||
$lbl = New-Object System.Windows.Controls.TextBlock
|
||||
$lbl.Text = $labelText
|
||||
$lbl.Style = $Window.Resources['LabelStyle']
|
||||
$labelName = "$comboName`_Label"
|
||||
$lbl.Name = $labelName
|
||||
|
||||
$lblBorder.Child = $lbl
|
||||
$parent.Children.Add($lblBorder) | Out-Null
|
||||
|
||||
# Register the label border with the window's name scope
|
||||
try {
|
||||
[System.Windows.NameScope]::SetNameScope($lblBorder, [System.Windows.NameScope]::GetNameScope($Window))
|
||||
$Window.RegisterName($lblBorderName, $lblBorder)
|
||||
}
|
||||
catch {
|
||||
# Name might already be registered, ignore
|
||||
}
|
||||
|
||||
$combo = New-Object System.Windows.Controls.ComboBox
|
||||
$combo.Name = $comboName
|
||||
$combo.SetValue([System.Windows.Automation.AutomationProperties]::NameProperty, $labelText)
|
||||
foreach ($item in $items) { $comboItem = New-Object System.Windows.Controls.ComboBoxItem; $comboItem.Content = $item; $combo.Items.Add($comboItem) | Out-Null }
|
||||
$combo.SelectedIndex = 0
|
||||
$parent.Children.Add($combo) | Out-Null
|
||||
|
||||
# Register the combo box with the window's name scope
|
||||
try {
|
||||
[System.Windows.NameScope]::SetNameScope($combo, [System.Windows.NameScope]::GetNameScope($Window))
|
||||
$Window.RegisterName($comboName, $combo)
|
||||
}
|
||||
catch {
|
||||
# Name might already be registered, ignore
|
||||
}
|
||||
|
||||
return $combo
|
||||
}
|
||||
|
||||
function GetWikiUrlForCategory($category) {
|
||||
if (-not $category) { return 'https://github.com/Raphire/Win11Debloat/wiki/Features' }
|
||||
|
||||
$slug = $category.ToLowerInvariant()
|
||||
$slug = $slug -replace '&', ''
|
||||
$slug = $slug -replace '[^a-z0-9\s-]', ''
|
||||
$slug = $slug -replace '\s', '-'
|
||||
|
||||
return "https://github.com/Raphire/Win11Debloat/wiki/Features#$slug"
|
||||
}
|
||||
|
||||
function GetOrCreateCategoryCard($categoryObj) {
|
||||
$categoryName = $categoryObj.Name
|
||||
$categoryIcon = $categoryObj.Icon
|
||||
|
||||
if ($script:CategoryCardMap.ContainsKey($categoryName)) { return $script:CategoryCardMap[$categoryName] }
|
||||
|
||||
# Create a new card Border + StackPanel and add to shortest column
|
||||
$target = $columns | Sort-Object @{Expression = { $_.Children.Count }; Ascending = $true }, @{Expression = { $columns.IndexOf($_) }; Ascending = $true } | Select-Object -First 1
|
||||
|
||||
$border = New-Object System.Windows.Controls.Border
|
||||
$border.Style = $Window.Resources['CategoryCardBorderStyle']
|
||||
$border.Tag = 'DynamicCategory'
|
||||
|
||||
$panel = New-Object System.Windows.Controls.StackPanel
|
||||
$safe = ($categoryName -replace '[^a-zA-Z0-9_]', '_')
|
||||
$panel.Name = "Category_{0}_Panel" -f $safe
|
||||
|
||||
$headerRow = New-Object System.Windows.Controls.StackPanel
|
||||
$headerRow.Orientation = 'Horizontal'
|
||||
|
||||
# Add category icon
|
||||
$icon = New-Object System.Windows.Controls.TextBlock
|
||||
# Convert HTML entity to character (e.g.,  -> actual character)
|
||||
if ($categoryIcon -match '&#x([0-9A-Fa-f]+);') {
|
||||
$hexValue = [Convert]::ToInt32($matches[1], 16)
|
||||
$icon.Text = [char]$hexValue
|
||||
}
|
||||
$icon.Style = $Window.Resources['CategoryHeaderIcon']
|
||||
$headerRow.Children.Add($icon) | Out-Null
|
||||
|
||||
$header = New-Object System.Windows.Controls.TextBlock
|
||||
$header.Text = $categoryName
|
||||
$header.Style = $Window.Resources['CategoryHeaderTextBlock']
|
||||
$headerRow.Children.Add($header) | Out-Null
|
||||
|
||||
$helpIcon = New-Object System.Windows.Controls.TextBlock
|
||||
$helpIcon.Text = '(?)'
|
||||
$helpIcon.Style = $Window.Resources['CategoryHelpLinkTextStyle']
|
||||
|
||||
$helpBtn = New-Object System.Windows.Controls.Button
|
||||
$helpBtn.Content = $helpIcon
|
||||
$helpBtn.ToolTip = "Open wiki for more info on '$categoryName' tweaks"
|
||||
$helpBtn.Tag = (GetWikiUrlForCategory -category $categoryName)
|
||||
$helpBtn.Style = $Window.Resources['CategoryHelpLinkButtonStyle']
|
||||
$helpBtn.Add_Click({
|
||||
param($button, $e)
|
||||
if ($button.Tag) { Start-Process $button.Tag }
|
||||
})
|
||||
$headerRow.Children.Add($helpBtn) | Out-Null
|
||||
|
||||
$panel.Children.Add($headerRow) | Out-Null
|
||||
|
||||
$border.Child = $panel
|
||||
$target.Children.Add($border) | Out-Null
|
||||
|
||||
$script:CategoryCardMap[$categoryName] = $panel
|
||||
return $panel
|
||||
}
|
||||
|
||||
# Determine categories present (from lists and features)
|
||||
$categoriesPresent = @{}
|
||||
if ($featuresJson.UiGroups) {
|
||||
foreach ($g in $featuresJson.UiGroups) { if ($g.Category) { $categoriesPresent[$g.Category] = $true } }
|
||||
}
|
||||
foreach ($f in $featuresJson.Features) { if ($f.Category) { $categoriesPresent[$f.Category] = $true } }
|
||||
|
||||
# Create cards in the order defined in Features.json Categories (if present)
|
||||
$orderedCategories = @()
|
||||
if ($featuresJson.Categories) {
|
||||
foreach ($c in $featuresJson.Categories) {
|
||||
$categoryName = if ($c -is [string]) { $c } else { $c.Name }
|
||||
if ($categoriesPresent.ContainsKey($categoryName)) {
|
||||
# Store the full category object (or create one with default icon for string categories)
|
||||
$categoryObj = if ($c -is [string]) { @{Name = $c; Icon = '' } } else { $c }
|
||||
$orderedCategories += $categoryObj
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
# For backward compatibility, create category objects from keys
|
||||
foreach ($catName in $categoriesPresent.Keys) {
|
||||
$orderedCategories += @{Name = $catName; Icon = '' }
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($categoryObj in $orderedCategories) {
|
||||
$categoryName = $categoryObj.Name
|
||||
|
||||
# Create/get card for this category
|
||||
$panel = GetOrCreateCategoryCard -categoryObj $categoryObj
|
||||
if (-not $panel) { continue }
|
||||
|
||||
# Collect groups and features for this category, then sort by priority
|
||||
$categoryItems = @()
|
||||
|
||||
# Add any groups for this category
|
||||
if ($featuresJson.UiGroups) {
|
||||
$groupIndex = 0
|
||||
foreach ($group in $featuresJson.UiGroups) {
|
||||
if ($group.Category -ne $categoryName) { $groupIndex++; continue }
|
||||
$categoryItems += [PSCustomObject]@{
|
||||
Type = 'group'
|
||||
Data = $group
|
||||
Priority = if ($null -ne $group.Priority) { $group.Priority } else { [int]::MaxValue }
|
||||
OriginalIndex = $groupIndex
|
||||
}
|
||||
$groupIndex++
|
||||
}
|
||||
}
|
||||
|
||||
# Add individual features for this category
|
||||
$featureIndex = 0
|
||||
foreach ($feature in $featuresJson.Features) {
|
||||
if ($feature.Category -ne $categoryName) { $featureIndex++; continue }
|
||||
|
||||
# Check version and feature compatibility using Features.json
|
||||
if (($feature.MinVersion -and $WinVersion -lt $feature.MinVersion) -or ($feature.MaxVersion -and $WinVersion -gt $feature.MaxVersion) -or ($feature.FeatureId -eq 'DisableModernStandbyNetworking' -and (-not $script:ModernStandbySupported))) {
|
||||
$featureIndex++; continue
|
||||
}
|
||||
|
||||
# Skip if feature part of a group
|
||||
$inGroup = $false
|
||||
if ($featuresJson.UiGroups) {
|
||||
foreach ($g in $featuresJson.UiGroups) { foreach ($val in $g.Values) { if ($val.FeatureIds -contains $feature.FeatureId) { $inGroup = $true; break } }; if ($inGroup) { break } }
|
||||
}
|
||||
if ($inGroup) { $featureIndex++; continue }
|
||||
|
||||
$categoryItems += [PSCustomObject]@{
|
||||
Type = 'feature'
|
||||
Data = $feature
|
||||
Priority = if ($null -ne $feature.Priority) { $feature.Priority } else { [int]::MaxValue }
|
||||
OriginalIndex = $featureIndex
|
||||
}
|
||||
$featureIndex++
|
||||
}
|
||||
|
||||
# Sort by priority first, then by original index for items with same/no priority
|
||||
$sortedItems = $categoryItems | Sort-Object -Property Priority, OriginalIndex
|
||||
|
||||
# Render sorted items
|
||||
foreach ($item in $sortedItems) {
|
||||
if ($item.Type -eq 'group') {
|
||||
$group = $item.Data
|
||||
$items = @('No Change') + ($group.Values | ForEach-Object { $_.Label })
|
||||
$comboName = 'Group_{0}Combo' -f $group.GroupId
|
||||
$combo = CreateLabeledCombo -parent $panel -labelText $group.Label -comboName $comboName -items $items
|
||||
# attach tooltip from UiGroups if present
|
||||
if ($group.ToolTip) {
|
||||
$tipBlock = New-Object System.Windows.Controls.TextBlock
|
||||
$tipBlock.Text = $group.ToolTip
|
||||
$tipBlock.TextWrapping = 'Wrap'
|
||||
$tipBlock.MaxWidth = 420
|
||||
$combo.ToolTip = $tipBlock
|
||||
$lblBorderObj = $null
|
||||
try { $lblBorderObj = $Window.FindName("$comboName`_LabelBorder") } catch {}
|
||||
if ($lblBorderObj) { $lblBorderObj.ToolTip = $tipBlock }
|
||||
}
|
||||
$script:UiControlMappings[$comboName] = @{ Type = 'group'; Values = $group.Values; Label = $group.Label; Category = $categoryName }
|
||||
}
|
||||
elseif ($item.Type -eq 'feature') {
|
||||
$feature = $item.Data
|
||||
$opt = 'Apply'
|
||||
if ($feature.FeatureId -match '^Disable') { $opt = 'Disable' } elseif ($feature.FeatureId -match '^Enable') { $opt = 'Enable' }
|
||||
$items = @('No Change', $opt)
|
||||
$comboName = ("Feature_{0}_Combo" -f $feature.FeatureId) -replace '[^a-zA-Z0-9_]', ''
|
||||
$combo = CreateLabeledCombo -parent $panel -labelText $feature.Label -comboName $comboName -items $items
|
||||
# attach tooltip from Features.json if present, and include the disabled-state reason
|
||||
if ($feature.ToolTip -or $feature.DisableWhenApplied -eq $true) {
|
||||
$tooltipText = $feature.ToolTip
|
||||
if ($feature.DisableWhenApplied -eq $true) {
|
||||
$tooltipText = "This tweak is already applied and cannot be undone automatically. Visit the Win11Debloat wiki for instructions on how to manually revert this change."
|
||||
}
|
||||
|
||||
$tipBlock = New-Object System.Windows.Controls.TextBlock
|
||||
$tipBlock.Text = $tooltipText
|
||||
$tipBlock.TextWrapping = 'Wrap'
|
||||
$tipBlock.MaxWidth = 420
|
||||
$combo.ToolTip = $tipBlock
|
||||
[System.Windows.Controls.ToolTipService]::SetShowOnDisabled($combo, $true)
|
||||
$lblBorderObj = $null
|
||||
try { $lblBorderObj = $Window.FindName("$comboName`_LabelBorder") } catch {}
|
||||
if ($lblBorderObj) { $lblBorderObj.ToolTip = $tipBlock }
|
||||
}
|
||||
$script:UiControlMappings[$comboName] = @{ Type = 'feature'; FeatureId = $feature.FeatureId; Label = $feature.Label; Category = $categoryName }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Build a feature-label lookup so GenerateOverview can resolve feature IDs without reloading JSON
|
||||
$script:FeatureLabelLookup = @{}
|
||||
$script:UndoFeatureLabelLookup = @{}
|
||||
foreach ($f in $featuresJson.Features) {
|
||||
$script:FeatureLabelLookup[$f.FeatureId] = $f.Label
|
||||
$script:UndoFeatureLabelLookup[$f.FeatureId] = $f.UndoLabel
|
||||
}
|
||||
}
|
||||
|
||||
function Update-CurrentTweakSystemState {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[bool]$ApplyToUi
|
||||
)
|
||||
|
||||
if (-not $script:UiControlMappings) { return }
|
||||
if (-not $script:Features) { return }
|
||||
|
||||
$featuresJson = LoadJsonFile -filePath $script:FeaturesFilePath -expectedVersion "1.0"
|
||||
if (-not $featuresJson) { return }
|
||||
|
||||
$groupMap = @{}
|
||||
if ($featuresJson.UiGroups) {
|
||||
foreach ($g in $featuresJson.UiGroups) {
|
||||
$groupMap[$g.GroupId] = $g
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($controlName in $script:UiControlMappings.Keys) {
|
||||
$control = $Window.FindName($controlName)
|
||||
if (-not $control) { continue }
|
||||
$mapping = $script:UiControlMappings[$controlName]
|
||||
|
||||
if ($control -is [System.Windows.Controls.CheckBox] -and $mapping.Type -eq 'feature') {
|
||||
$applied = $false
|
||||
try { $applied = [bool](Test-FeatureApplied -FeatureId $mapping.FeatureId) } catch {}
|
||||
$featureObj = $script:Features[$mapping.FeatureId]
|
||||
$disableWhenApplied = $featureObj -and $featureObj.DisableWhenApplied -eq $true
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'SystemState' -Value $applied -Force
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'DisableWhenApplied' -Value $disableWhenApplied -Force
|
||||
|
||||
if ($ApplyToUi) {
|
||||
$control.IsChecked = $applied
|
||||
$control.IsEnabled = -not ($applied -and $disableWhenApplied)
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'InitialState' -Value $applied -Force
|
||||
}
|
||||
}
|
||||
elseif ($control -is [System.Windows.Controls.ComboBox] -and $mapping.Type -eq 'group') {
|
||||
$groupId = $null
|
||||
if ($controlName -match '^Group_(.+)Combo$') { $groupId = $matches[1] }
|
||||
$activeIndex = 0
|
||||
if ($groupId -and $groupMap.ContainsKey($groupId)) {
|
||||
try { $activeIndex = Get-CurrentGroupActiveIndex -Group $groupMap[$groupId] } catch {}
|
||||
}
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'SystemIndex' -Value $activeIndex -Force
|
||||
|
||||
if ($ApplyToUi) {
|
||||
$control.SelectedIndex = $activeIndex
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'InitialIndex' -Value $activeIndex -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Load-CurrentTweakStateIntoUI {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
Update-CurrentTweakSystemState -Window $Window -ApplyToUi:$true
|
||||
}
|
||||
|
||||
function Reset-TweaksToSystemState {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[bool]$LoadSystemState
|
||||
)
|
||||
|
||||
if (-not $script:UiControlMappings) { return }
|
||||
|
||||
foreach ($controlName in $script:UiControlMappings.Keys) {
|
||||
$control = $Window.FindName($controlName)
|
||||
if (-not $control) { continue }
|
||||
|
||||
if ($control -is [System.Windows.Controls.CheckBox]) {
|
||||
if ($LoadSystemState) {
|
||||
# Set checkbox to the currently applied state from registry
|
||||
$applied = if ($null -ne $control.PSObject.Properties['SystemState']) { [bool]$control.SystemState } else { $false }
|
||||
$disableWhenApplied = $null -ne $control.PSObject.Properties['DisableWhenApplied'] -and [bool]$control.DisableWhenApplied
|
||||
$control.IsChecked = $applied
|
||||
$control.IsEnabled = -not ($applied -and $disableWhenApplied)
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'InitialState' -Value $applied -Force
|
||||
}
|
||||
else {
|
||||
# Clear the checkbox
|
||||
$control.IsChecked = $false
|
||||
$control.IsEnabled = $true
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'InitialState' -Value $false -Force
|
||||
}
|
||||
}
|
||||
elseif ($control -is [System.Windows.Controls.ComboBox]) {
|
||||
if ($LoadSystemState) {
|
||||
# Set combobox to the currently applied state from registry
|
||||
$idx = if ($null -ne $control.PSObject.Properties['SystemIndex']) { [int]$control.SystemIndex } else { 0 }
|
||||
$control.SelectedIndex = $idx
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'InitialIndex' -Value $idx -Force
|
||||
}
|
||||
else {
|
||||
# Reset to first item (No Change)
|
||||
$control.SelectedIndex = 0
|
||||
Add-Member -InputObject $control -MemberType NoteProperty -Name 'InitialIndex' -Value 0 -Force
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Update-TweaksResponsiveColumns {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
$tweaksGrid = $Window.FindName('TweaksGrid')
|
||||
$col0 = $Window.FindName('Column0Panel')
|
||||
$col1 = $Window.FindName('Column1Panel')
|
||||
$col2 = $Window.FindName('Column2Panel')
|
||||
|
||||
if (-not $tweaksGrid -or -not $col0 -or -not $col1 -or -not $col2) { return }
|
||||
if ($tweaksGrid.ColumnDefinitions.Count -lt 3) { return }
|
||||
if ($null -eq $script:TweaksCardsMovedFromCol2) { $script:TweaksCardsMovedFromCol2 = @() }
|
||||
|
||||
$useTwoColumns = $Window.ActualWidth -lt 1200
|
||||
if ($script:TweaksCompactMode -eq $useTwoColumns) { return }
|
||||
$script:TweaksCompactMode = $useTwoColumns
|
||||
|
||||
if ($useTwoColumns) {
|
||||
$tweaksGrid.ColumnDefinitions[0].Width = [System.Windows.GridLength]::new(1, [System.Windows.GridUnitType]::Star)
|
||||
$tweaksGrid.ColumnDefinitions[1].Width = [System.Windows.GridLength]::new(1, [System.Windows.GridUnitType]::Star)
|
||||
$tweaksGrid.ColumnDefinitions[2].Width = [System.Windows.GridLength]::new(0)
|
||||
$col2.Visibility = 'Collapsed'
|
||||
|
||||
# Move third-column cards once when entering compact mode.
|
||||
$cardsToMove = @($col2.Children) | Where-Object { $_ -is [System.Windows.UIElement] }
|
||||
$script:TweaksCardsMovedFromCol2 = @($cardsToMove)
|
||||
$col2.Children.Clear()
|
||||
$targetColumns = @($col0, $col1)
|
||||
foreach ($card in $cardsToMove) {
|
||||
$target = $targetColumns |
|
||||
Sort-Object @{Expression = { $_.Children.Count }; Ascending = $true }, @{Expression = { $targetColumns.IndexOf($_) }; Ascending = $true } |
|
||||
Select-Object -First 1
|
||||
$target.Children.Add($card) | Out-Null
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
$tweaksGrid.ColumnDefinitions[0].Width = [System.Windows.GridLength]::new(1, [System.Windows.GridUnitType]::Star)
|
||||
$tweaksGrid.ColumnDefinitions[1].Width = [System.Windows.GridLength]::new(1, [System.Windows.GridUnitType]::Star)
|
||||
$tweaksGrid.ColumnDefinitions[2].Width = [System.Windows.GridLength]::new(1, [System.Windows.GridUnitType]::Star)
|
||||
$col2.Visibility = 'Visible'
|
||||
|
||||
foreach ($card in (@($script:TweaksCardsMovedFromCol2) | Where-Object { $_ -is [System.Windows.UIElement] })) {
|
||||
if ($col0.Children.Contains($card)) {
|
||||
$col0.Children.Remove($card) | Out-Null
|
||||
}
|
||||
elseif ($col1.Children.Contains($card)) {
|
||||
$col1.Children.Remove($card) | Out-Null
|
||||
}
|
||||
$col2.Children.Add($card) | Out-Null
|
||||
}
|
||||
$script:TweaksCardsMovedFromCol2 = @()
|
||||
}
|
||||
|
||||
function Clear-TweakSelections {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
if (-not $script:UiControlMappings) { return }
|
||||
|
||||
foreach ($controlName in $script:UiControlMappings.Keys) {
|
||||
$control = $Window.FindName($controlName)
|
||||
if ($control -is [System.Windows.Controls.CheckBox]) {
|
||||
$control.IsChecked = $false
|
||||
$control.IsEnabled = $true
|
||||
}
|
||||
elseif ($control -is [System.Windows.Controls.ComboBox]) {
|
||||
$control.SelectedIndex = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Clear-TweakHighlights {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
$col0 = $Window.FindName('Column0Panel')
|
||||
$col1 = $Window.FindName('Column1Panel')
|
||||
$col2 = $Window.FindName('Column2Panel')
|
||||
$columns = @($col0, $col1, $col2) | Where-Object { $_ -ne $null }
|
||||
foreach ($column in $columns) {
|
||||
foreach ($card in $column.Children) {
|
||||
if ($card -is [System.Windows.Controls.Border] -and $card.Child -is [System.Windows.Controls.StackPanel]) {
|
||||
foreach ($control in $card.Child.Children) {
|
||||
if ($control -is [System.Windows.Controls.CheckBox] -or
|
||||
($control -is [System.Windows.Controls.Border] -and $control.Name -like '*_LabelBorder')) {
|
||||
$control.Background = [System.Windows.Media.Brushes]::Transparent
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Test-ComboBoxContainsMatch {
|
||||
param ([System.Windows.Controls.ComboBox]$ComboBox, [string]$SearchText)
|
||||
|
||||
foreach ($item in $ComboBox.Items) {
|
||||
$itemText = if ($item -is [System.Windows.Controls.ComboBoxItem]) { $item.Content.ToString().ToLower() } else { $item.ToString().ToLower() }
|
||||
if ($itemText.Contains($SearchText)) { return $true }
|
||||
}
|
||||
return $false
|
||||
}
|
||||
215
Scripts/GUI/MainWindow-WindowChrome.ps1
Normal file
215
Scripts/GUI/MainWindow-WindowChrome.ps1
Normal file
@@ -0,0 +1,215 @@
|
||||
# MainWindow-WindowChrome.ps1
|
||||
# Window sizing, DPI-aware coordinate conversion, maximized-window taskbar-constraint helpers, and UI animations.
|
||||
|
||||
function Register-MaximizedWindowHelper {
|
||||
if (-not ([System.Management.Automation.PSTypeName]'Win11Debloat.MaximizedWindowHelper').Type) {
|
||||
Add-Type -Namespace Win11Debloat -Name MaximizedWindowHelper `
|
||||
-ReferencedAssemblies 'PresentationFramework','System.Windows.Forms','System.Drawing' `
|
||||
-MemberDefinition @'
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
||||
private struct MINMAXINFO {
|
||||
public POINT ptReserved, ptMaxSize, ptMaxPosition, ptMinTrackSize, ptMaxTrackSize;
|
||||
}
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
||||
private struct POINT { public int x, y; }
|
||||
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")]
|
||||
private static extern System.IntPtr MonitorFromWindow(System.IntPtr hwnd, uint dwFlags);
|
||||
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
|
||||
private static extern bool GetMonitorInfo(System.IntPtr hMonitor, ref MONITORINFO lpmi);
|
||||
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
|
||||
private struct RECT {
|
||||
public int Left, Top, Right, Bottom;
|
||||
}
|
||||
|
||||
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
|
||||
private struct MONITORINFO {
|
||||
public int cbSize;
|
||||
public RECT rcMonitor;
|
||||
public RECT rcWork;
|
||||
public uint dwFlags;
|
||||
}
|
||||
|
||||
public static System.IntPtr WmGetMinMaxInfoHook(
|
||||
System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) {
|
||||
if (msg == 0x0024) { // WM_GETMINMAXINFO
|
||||
var mmi = (MINMAXINFO)System.Runtime.InteropServices.Marshal.PtrToStructure(
|
||||
lParam, typeof(MINMAXINFO));
|
||||
|
||||
const uint MONITOR_DEFAULTTONEAREST = 0x00000002;
|
||||
var monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
|
||||
var monitorInfo = new MONITORINFO();
|
||||
monitorInfo.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(MONITORINFO));
|
||||
|
||||
if (monitor != System.IntPtr.Zero && GetMonitorInfo(monitor, ref monitorInfo)) {
|
||||
mmi.ptMaxPosition.x = monitorInfo.rcWork.Left - monitorInfo.rcMonitor.Left;
|
||||
mmi.ptMaxPosition.y = monitorInfo.rcWork.Top - monitorInfo.rcMonitor.Top;
|
||||
mmi.ptMaxSize.x = monitorInfo.rcWork.Right - monitorInfo.rcWork.Left;
|
||||
mmi.ptMaxSize.y = monitorInfo.rcWork.Bottom - monitorInfo.rcWork.Top;
|
||||
}
|
||||
else {
|
||||
var screen = System.Windows.Forms.Screen.FromHandle(hwnd);
|
||||
var wa = screen.WorkingArea;
|
||||
var bounds = screen.Bounds;
|
||||
mmi.ptMaxPosition.x = wa.Left - bounds.Left;
|
||||
mmi.ptMaxPosition.y = wa.Top - bounds.Top;
|
||||
mmi.ptMaxSize.x = wa.Width;
|
||||
mmi.ptMaxSize.y = wa.Height;
|
||||
}
|
||||
|
||||
System.Runtime.InteropServices.Marshal.StructureToPtr(mmi, lParam, true);
|
||||
}
|
||||
return System.IntPtr.Zero;
|
||||
}
|
||||
'@
|
||||
}
|
||||
}
|
||||
|
||||
# Convert screen-pixel coordinates to WPF device-independent pixels (DIP)
|
||||
function ConvertTo-ScreenPointToDip {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[double]$X,
|
||||
[double]$Y
|
||||
)
|
||||
|
||||
$source = [System.Windows.PresentationSource]::FromVisual($Window)
|
||||
if ($null -eq $source -or $null -eq $source.CompositionTarget) {
|
||||
return [System.Windows.Point]::new($X, $Y)
|
||||
}
|
||||
|
||||
return $source.CompositionTarget.TransformFromDevice.Transform([System.Windows.Point]::new($X, $Y))
|
||||
}
|
||||
|
||||
# Convert screen-pixel size to WPF device-independent size
|
||||
function ConvertTo-ScreenPixelsToDip {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[double]$Width,
|
||||
[double]$Height
|
||||
)
|
||||
|
||||
$topLeft = ConvertTo-ScreenPointToDip -Window $Window -X 0 -Y 0
|
||||
$bottomRight = ConvertTo-ScreenPointToDip -Window $Window -X $Width -Y $Height
|
||||
return [System.Windows.Size]::new($bottomRight.X - $topLeft.X, $bottomRight.Y - $topLeft.Y)
|
||||
}
|
||||
|
||||
# Get the screen that currently contains the window
|
||||
function Get-WindowScreen {
|
||||
param([System.Windows.Window]$Window)
|
||||
|
||||
$hwnd = (New-Object System.Windows.Interop.WindowInteropHelper($Window)).Handle
|
||||
if ($hwnd -eq [IntPtr]::Zero) {
|
||||
return $null
|
||||
}
|
||||
|
||||
return [System.Windows.Forms.Screen]::FromHandle($hwnd)
|
||||
}
|
||||
|
||||
# Update window border/corner chrome when transitioning between Normal and Maximized
|
||||
function Update-MainWindowChrome {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.Border]$MainBorder,
|
||||
[System.Windows.Controls.Border]$TitleBarBackground,
|
||||
[object]$NormalWindowShadow
|
||||
)
|
||||
|
||||
$windowStateMaximized = [System.Windows.WindowState]::Maximized
|
||||
$chrome = [System.Windows.Shell.WindowChrome]::GetWindowChrome($Window)
|
||||
|
||||
if ($Window.WindowState -eq $windowStateMaximized) {
|
||||
$MainBorder.Margin = [System.Windows.Thickness]::new(0)
|
||||
$MainBorder.BorderThickness = [System.Windows.Thickness]::new(0)
|
||||
$MainBorder.CornerRadius = [System.Windows.CornerRadius]::new(0)
|
||||
$MainBorder.Effect = $null
|
||||
$TitleBarBackground.CornerRadius = [System.Windows.CornerRadius]::new(0)
|
||||
# Zero out resize borders when maximized so the entire title bar row is draggable
|
||||
if ($chrome) { $chrome.ResizeBorderThickness = [System.Windows.Thickness]::new(0) }
|
||||
}
|
||||
else {
|
||||
$MainBorder.Margin = [System.Windows.Thickness]::new(0)
|
||||
$MainBorder.BorderThickness = [System.Windows.Thickness]::new(1)
|
||||
$MainBorder.CornerRadius = [System.Windows.CornerRadius]::new(8)
|
||||
$MainBorder.Effect = $NormalWindowShadow
|
||||
$TitleBarBackground.CornerRadius = [System.Windows.CornerRadius]::new(8, 8, 0, 0)
|
||||
if ($chrome) { $chrome.ResizeBorderThickness = [System.Windows.Thickness]::new(5) }
|
||||
}
|
||||
}
|
||||
|
||||
# Set the initial window size and center on screen (normal state only)
|
||||
function Set-MainWindowInitialSize {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[double]$InitialNormalMaxWidth = 1400.0
|
||||
)
|
||||
|
||||
if ($Window.WindowState -ne [System.Windows.WindowState]::Normal) {
|
||||
return
|
||||
}
|
||||
|
||||
$screen = Get-WindowScreen -Window $Window
|
||||
if ($null -eq $screen) {
|
||||
return
|
||||
}
|
||||
|
||||
$workingAreaTopLeftDip = ConvertTo-ScreenPointToDip -Window $Window -X $screen.WorkingArea.Left -Y $screen.WorkingArea.Top
|
||||
$workingAreaDip = ConvertTo-ScreenPixelsToDip -Window $Window -Width $screen.WorkingArea.Width -Height $screen.WorkingArea.Height
|
||||
$Window.Width = [Math]::Min($InitialNormalMaxWidth, $workingAreaDip.Width)
|
||||
$Window.Left = $workingAreaTopLeftDip.X + (($workingAreaDip.Width - $Window.Width) / 2)
|
||||
}
|
||||
|
||||
# Update the content grid margin to constrain max content width
|
||||
function Update-MainWindowContentMargin {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.Grid]$ContentGrid,
|
||||
[double]$MaxContentWidth = 1600.0
|
||||
)
|
||||
|
||||
$w = $Window.ActualWidth
|
||||
if ($w -gt $MaxContentWidth) {
|
||||
$gutter = [Math]::Floor(($w - $MaxContentWidth) / 2)
|
||||
$ContentGrid.Margin = [System.Windows.Thickness]::new($gutter, 0, $gutter, 0)
|
||||
}
|
||||
else {
|
||||
$ContentGrid.Margin = [System.Windows.Thickness]::new(0)
|
||||
}
|
||||
}
|
||||
|
||||
# Vertically center the home content panel
|
||||
function Update-MainWindowHomeContentPosition {
|
||||
param(
|
||||
[System.Windows.Window]$Window,
|
||||
[System.Windows.Controls.Panel]$HomeContentPanel
|
||||
)
|
||||
|
||||
if ($HomeContentPanel) {
|
||||
$availableHeight = $Window.ActualHeight - 32 # subtract title bar height
|
||||
if ($availableHeight -gt 0) {
|
||||
$topMargin = ($availableHeight - 584) * 0.5
|
||||
$HomeContentPanel.Margin = [System.Windows.Thickness]::new(0, $topMargin, 0, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Start-DropdownArrowAnimation {
|
||||
param(
|
||||
[System.Windows.Controls.TextBlock]$Arrow,
|
||||
[double]$Angle
|
||||
)
|
||||
|
||||
if (-not $Arrow) { return }
|
||||
|
||||
$animation = New-Object System.Windows.Media.Animation.DoubleAnimation
|
||||
$animation.To = $Angle
|
||||
$animation.Duration = [System.Windows.Duration]::new([System.TimeSpan]::FromMilliseconds(200))
|
||||
|
||||
$ease = New-Object System.Windows.Media.Animation.CubicEase
|
||||
$ease.EasingMode = 'EaseOut'
|
||||
$animation.EasingFunction = $ease
|
||||
|
||||
$Arrow.RenderTransform.BeginAnimation([System.Windows.Media.RotateTransform]::AngleProperty, $animation)
|
||||
}
|
||||
175
Scripts/GUI/RestoreBackupDialogFeatureLists.ps1
Normal file
175
Scripts/GUI/RestoreBackupDialogFeatureLists.ps1
Normal file
@@ -0,0 +1,175 @@
|
||||
function New-RestoreDialogState {
|
||||
param(
|
||||
[string]$Result = 'Cancel',
|
||||
[string]$SelectedFile = $null,
|
||||
$Backup = $null
|
||||
)
|
||||
|
||||
return @{ Result = $Result; SelectedFile = $SelectedFile; Backup = $Backup }
|
||||
}
|
||||
|
||||
function Get-RestoreDialogFeatureDefinition {
|
||||
param(
|
||||
[string]$FeatureId,
|
||||
[hashtable]$Features
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($FeatureId) -or -not $Features) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if ($Features.ContainsKey($FeatureId)) {
|
||||
return $Features[$FeatureId]
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Test-RestoreDialogFeatureCanAutoRevert {
|
||||
param(
|
||||
[string]$FeatureId,
|
||||
[hashtable]$Features
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($FeatureId)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
$featureDefinition = Get-RestoreDialogFeatureDefinition -FeatureId $FeatureId -Features $Features
|
||||
if ($featureDefinition) {
|
||||
return -not [string]::IsNullOrWhiteSpace([string]$featureDefinition.RegistryKey)
|
||||
}
|
||||
|
||||
return $false
|
||||
}
|
||||
|
||||
function Get-RestoreDialogFeatureDisplayLabel {
|
||||
param(
|
||||
[string]$FeatureId,
|
||||
[hashtable]$Features
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($FeatureId)) {
|
||||
return 'Unknown feature'
|
||||
}
|
||||
|
||||
$featureDefinition = Get-RestoreDialogFeatureDefinition -FeatureId $FeatureId -Features $Features
|
||||
if ($featureDefinition -and -not [string]::IsNullOrWhiteSpace([string]$featureDefinition.Label)) {
|
||||
return [string]$featureDefinition.Label
|
||||
}
|
||||
|
||||
return $FeatureId
|
||||
}
|
||||
|
||||
function Test-RestoreDialogFeatureVisibleInOverview {
|
||||
param(
|
||||
[string]$FeatureId,
|
||||
[hashtable]$Features
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($FeatureId)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
$featureDefinition = Get-RestoreDialogFeatureDefinition -FeatureId $FeatureId -Features $Features
|
||||
if (-not $featureDefinition) {
|
||||
return $false
|
||||
}
|
||||
|
||||
return -not [string]::IsNullOrWhiteSpace([string]$featureDefinition.Category)
|
||||
}
|
||||
|
||||
function Get-SelectedForwardFeatureIdsFromBackup {
|
||||
param($SelectedBackup)
|
||||
|
||||
$selectedFeatureIds = New-Object System.Collections.Generic.List[string]
|
||||
$seenSelectedFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
|
||||
foreach ($featureId in @($SelectedBackup.SelectedFeatures)) {
|
||||
if ([string]::IsNullOrWhiteSpace([string]$featureId)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$normalizedId = [string]$featureId
|
||||
if ($seenSelectedFeatureIds.Add($normalizedId)) {
|
||||
$selectedFeatureIds.Add($normalizedId)
|
||||
}
|
||||
}
|
||||
|
||||
return @($selectedFeatureIds.ToArray())
|
||||
}
|
||||
|
||||
function Get-SelectedUndoFeatureIdsFromBackup {
|
||||
param($SelectedBackup)
|
||||
|
||||
$selectedUndoFeatureIds = New-Object System.Collections.Generic.List[string]
|
||||
$seenUndoFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
|
||||
foreach ($featureId in @($SelectedBackup.SelectedUndoFeatures)) {
|
||||
if ([string]::IsNullOrWhiteSpace([string]$featureId)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$normalizedId = [string]$featureId
|
||||
if ($seenUndoFeatureIds.Add($normalizedId)) {
|
||||
$selectedUndoFeatureIds.Add($normalizedId)
|
||||
}
|
||||
}
|
||||
|
||||
return @($selectedUndoFeatureIds.ToArray())
|
||||
}
|
||||
|
||||
function Get-CombinedSelectedFeatureIdsFromBackup {
|
||||
param($SelectedBackup)
|
||||
|
||||
$featureIds = New-Object System.Collections.Generic.List[string]
|
||||
$seenIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
|
||||
foreach ($featureId in @(Get-SelectedForwardFeatureIdsFromBackup -SelectedBackup $SelectedBackup) + @(Get-SelectedUndoFeatureIdsFromBackup -SelectedBackup $SelectedBackup)) {
|
||||
if ([string]::IsNullOrWhiteSpace([string]$featureId)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$normalizedId = [string]$featureId
|
||||
if ($seenIds.Add($normalizedId)) {
|
||||
$featureIds.Add($normalizedId)
|
||||
}
|
||||
}
|
||||
|
||||
return @($featureIds.ToArray())
|
||||
}
|
||||
|
||||
function Get-SelectedFeatureIdsFromBackup {
|
||||
param($SelectedBackup)
|
||||
|
||||
return @(Get-CombinedSelectedFeatureIdsFromBackup -SelectedBackup $SelectedBackup)
|
||||
}
|
||||
|
||||
function Get-RestoreBackupFeatureLists {
|
||||
param(
|
||||
[string[]]$SelectedFeatureIds,
|
||||
[hashtable]$Features
|
||||
)
|
||||
|
||||
$revertibleFeaturesList = @()
|
||||
$nonRevertibleFeaturesList = @()
|
||||
|
||||
foreach ($featureId in $SelectedFeatureIds) {
|
||||
if (-not (Test-RestoreDialogFeatureVisibleInOverview -FeatureId $featureId -Features $Features)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$displayItem = [PSCustomObject]@{ DisplayText = "- $(Get-RestoreDialogFeatureDisplayLabel -FeatureId $featureId -Features $Features)" }
|
||||
if (Test-RestoreDialogFeatureCanAutoRevert -FeatureId $featureId -Features $Features) {
|
||||
$revertibleFeaturesList += $displayItem
|
||||
}
|
||||
else {
|
||||
$nonRevertibleFeaturesList += $displayItem
|
||||
}
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
Revertible = @($revertibleFeaturesList)
|
||||
NonRevertible = @($nonRevertibleFeaturesList)
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,7 @@ function SetWindowThemeResources {
|
||||
$window.Resources.Add("ButtonPressed", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#3284cc")))
|
||||
$window.Resources.Add("CloseHover", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#c42b1c")))
|
||||
$window.Resources.Add("InformationIconColor", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#0078D4")))
|
||||
$window.Resources.Add("SuccessIconColor", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#107C10")))
|
||||
$window.Resources.Add("WarningIconColor", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#FFB900")))
|
||||
$window.Resources.Add("ErrorIconColor", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#E81123")))
|
||||
$window.Resources.Add("QuestionIconColor", [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#0078D4")))
|
||||
|
||||
@@ -130,12 +130,8 @@ function Show-AppSelectionWindow {
|
||||
return
|
||||
}
|
||||
|
||||
if ($selectedApps -contains "Microsoft.WindowsStore" -and -not $Silent) {
|
||||
$result = Show-MessageBox -Message 'Are you sure you wish to uninstall the Microsoft Store? This app cannot easily be reinstalled.' -Title 'Are you sure?' -Button 'YesNo' -Icon 'Warning' -Owner $window
|
||||
|
||||
if ($result -eq 'No') {
|
||||
return
|
||||
}
|
||||
if (-not (ConfirmUnsafeAppRemoval -SelectedApps $selectedApps -Owner $window)) {
|
||||
return
|
||||
}
|
||||
|
||||
SaveCustomAppsListToFile -appsList $selectedApps
|
||||
|
||||
@@ -123,6 +123,8 @@ function Show-ApplyModal {
|
||||
$applyWindow.Dispatcher.BeginInvoke([System.Windows.Threading.DispatcherPriority]::Background, [action]{
|
||||
try {
|
||||
ExecuteAllChanges
|
||||
|
||||
$registryImportFailureCount = [int]$script:RegistryImportFailures
|
||||
|
||||
# Restart explorer if requested
|
||||
if ($RestartExplorer -and -not $script:CancelRequested) {
|
||||
@@ -139,7 +141,7 @@ function Show-ApplyModal {
|
||||
Write-Host ""
|
||||
if ($script:CancelRequested) {
|
||||
Write-Host "Script execution was cancelled by the user. Some changes may not have been applied."
|
||||
} else {
|
||||
} elseif ($registryImportFailureCount -eq 0) {
|
||||
Write-Host "All changes have been applied successfully!"
|
||||
}
|
||||
|
||||
@@ -153,6 +155,11 @@ function Show-ApplyModal {
|
||||
$script:ApplyCompletionIconEl.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#e8912d"))
|
||||
$script:ApplyCompletionTitleEl.Text = "Cancelled"
|
||||
$script:ApplyCompletionMessageEl.Text = "Script execution was cancelled by the user."
|
||||
} elseif ($registryImportFailureCount -gt 0) {
|
||||
$script:ApplyCompletionIconEl.Text = [char]0xE7BA
|
||||
$script:ApplyCompletionIconEl.Foreground = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.ColorConverter]::ConvertFromString("#e8912d"))
|
||||
$script:ApplyCompletionTitleEl.Text = "Changes Applied with Errors"
|
||||
$script:ApplyCompletionMessageEl.Text = "$registryImportFailureCount registry change(s) failed. See console for details."
|
||||
} else {
|
||||
$script:ApplyCompletionTitleEl.Text = "Changes Applied"
|
||||
|
||||
@@ -162,7 +169,7 @@ function Show-ApplyModal {
|
||||
foreach ($paramKey in $script:Params.Keys) {
|
||||
if ($script:Features.ContainsKey($paramKey) -and $script:Features[$paramKey].RequiresReboot -eq $true) {
|
||||
$feature = $script:Features[$paramKey]
|
||||
$rebootFeatures += $feature.Action
|
||||
$rebootFeatures += "$($feature.Label)"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ function Show-ImportExportConfigWindow {
|
||||
[string]$Prompt,
|
||||
[string[]]$Categories = @('Applications', 'System Tweaks', 'Deployment Settings'),
|
||||
[string[]]$DisabledCategories = @(),
|
||||
[hashtable]$CategoryDetails = @()
|
||||
[hashtable]$CategoryDetails = @(),
|
||||
[string]$ActionLabel = 'OK'
|
||||
)
|
||||
|
||||
# Show overlay on owner window
|
||||
@@ -45,6 +46,14 @@ function Show-ImportExportConfigWindow {
|
||||
$dlg.Owner = $Owner
|
||||
SetWindowThemeResources -window $dlg -usesDarkMode $UsesDarkMode
|
||||
|
||||
# Copy the CheckBox default style from the main window so checkboxes get the themed template
|
||||
try {
|
||||
$mainCheckBoxStyle = $Owner.FindResource([type][System.Windows.Controls.CheckBox])
|
||||
if ($mainCheckBoxStyle) {
|
||||
$dlg.Resources.Add([type][System.Windows.Controls.CheckBox], $mainCheckBoxStyle)
|
||||
}
|
||||
} catch { }
|
||||
|
||||
# Populate named elements
|
||||
$dlg.Title = $Title
|
||||
$dlg.FindName('TitleText').Text = $Title
|
||||
@@ -70,7 +79,6 @@ function Show-ImportExportConfigWindow {
|
||||
$cb.FontSize = 14
|
||||
$cb.FontWeight = [System.Windows.FontWeights]::Medium
|
||||
$cb.Foreground = $dlg.FindResource('FgColor')
|
||||
$cb.Style = $window.Resources["AppsPanelCheckBoxStyle"]
|
||||
if ($DisabledCategories -contains $cat) {
|
||||
$cb.IsChecked = $false
|
||||
$cb.IsEnabled = $false
|
||||
@@ -98,6 +106,7 @@ function Show-ImportExportConfigWindow {
|
||||
|
||||
$okBtn = $dlg.FindName('OkButton')
|
||||
$cancelBtn = $dlg.FindName('CancelButton')
|
||||
$okBtn.Content = $ActionLabel
|
||||
$okBtn.Add_Click({ $dlg.Tag = 'OK'; $dlg.Close() })
|
||||
$cancelBtn.Add_Click({ $dlg.Tag = 'Cancel'; $dlg.Close() })
|
||||
|
||||
@@ -372,8 +381,11 @@ function Export-Configuration {
|
||||
$deploymentSettings = Get-DeploymentSettings -Owner $Owner -UserSelectionCombo $UserSelectionCombo -OtherUsernameTextBox $OtherUsernameTextBox
|
||||
$categoryDetails = Build-CategoryDetails -AppCount $selectedApps.Count -TweakCount $tweakSettings.Count -DeploymentSettings $deploymentSettings
|
||||
|
||||
$categories = Show-ImportExportConfigWindow -Owner $Owner -UsesDarkMode $UsesDarkMode -Title 'Export Configuration' -Prompt 'Select which settings to include in the export:' -DisabledCategories $disabledCategories -CategoryDetails $categoryDetails
|
||||
if (-not $categories) { return }
|
||||
$categories = Show-ImportExportConfigWindow -Owner $Owner -UsesDarkMode $UsesDarkMode -Title 'Export Configuration' -Prompt 'Select the settings you wish to include in your export.' -DisabledCategories $disabledCategories -CategoryDetails $categoryDetails -ActionLabel 'Export Settings'
|
||||
if (-not $categories) {
|
||||
Write-Host 'Export canceled.'
|
||||
return
|
||||
}
|
||||
|
||||
$config = @{ Version = '1.0' }
|
||||
|
||||
@@ -394,12 +406,19 @@ function Export-Configuration {
|
||||
$saveDialog.DefaultExt = '.json'
|
||||
$saveDialog.FileName = "Win11Debloat-Config-$(Get-Date -Format 'yyyyMMdd').json"
|
||||
|
||||
if ($saveDialog.ShowDialog($Owner) -ne $true) { return }
|
||||
if ($saveDialog.ShowDialog($Owner) -ne $true) {
|
||||
Write-Host 'Export save dialog canceled.'
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "Exporting configuration to '$($saveDialog.FileName)'... (Categories: $($categories -join ', '))"
|
||||
|
||||
if (SaveToFile -Config $config -FilePath $saveDialog.FileName) {
|
||||
Write-Host "Configuration exported successfully: $($saveDialog.FileName)"
|
||||
Show-MessageBox -Message "Configuration exported successfully." -Title 'Export Configuration' -Button 'OK' -Icon 'Information' | Out-Null
|
||||
}
|
||||
else {
|
||||
Write-Error "Failed to export configuration to '$($saveDialog.FileName)'"
|
||||
Show-MessageBox -Message "Failed to export configuration" -Title 'Error' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
}
|
||||
}
|
||||
@@ -418,36 +437,49 @@ function Import-Configuration {
|
||||
|
||||
# Show native open-file dialog
|
||||
$openDialog = New-Object Microsoft.Win32.OpenFileDialog
|
||||
$openDialog.Title = 'Import Configuration'
|
||||
$openDialog.Title = 'Select Configuration File'
|
||||
$openDialog.Filter = 'JSON files (*.json)|*.json|All files (*.*)|*.*'
|
||||
$openDialog.DefaultExt = '.json'
|
||||
|
||||
if ($openDialog.ShowDialog($Owner) -ne $true) { return }
|
||||
if ($openDialog.ShowDialog($Owner) -ne $true) {
|
||||
Write-Host 'Import file dialog canceled.'
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "Importing configuration from '$($openDialog.FileName)'..."
|
||||
|
||||
$config = LoadJsonFile -filePath $openDialog.FileName -expectedVersion '1.0'
|
||||
if (-not $config) {
|
||||
Show-MessageBox -Message "Failed to read configuration file" -Title 'Error' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
Write-Error "Failed to read configuration file '$($openDialog.FileName)'"
|
||||
Show-MessageBox -Message "Failed to read configuration file" -Title 'Invalid Config' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
return
|
||||
}
|
||||
|
||||
if (-not $config.Version) {
|
||||
Show-MessageBox -Message "Invalid configuration file format." -Title 'Error' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
Write-Error "Invalid configuration file format: '$($openDialog.FileName)'"
|
||||
Show-MessageBox -Message "Invalid configuration file format." -Title 'Invalid Config' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
return
|
||||
}
|
||||
|
||||
$availableCategories = Get-AvailableImportExportCategories -Config $config
|
||||
|
||||
if ($availableCategories.Count -eq 0) {
|
||||
Show-MessageBox -Message "The configuration file contains no importable data." -Title 'Import Configuration' -Button 'OK' -Icon 'Information' | Out-Null
|
||||
Write-Warning "Configuration file '$($openDialog.FileName)' contains no importable data."
|
||||
Show-MessageBox -Message "The selected file contains no importable data." -Title 'Invalid Config' -Button 'OK' -Icon 'Error' | Out-Null
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "Available categories in config: $($availableCategories -join ', ')"
|
||||
|
||||
$appCount = @($config.Apps | Where-Object { $_ -is [string] -and -not [string]::IsNullOrWhiteSpace($_) }).Count
|
||||
$tweakCount = @($config.Tweaks | Where-Object { $_ -and $_.Name -and $_.Value -eq $true }).Count
|
||||
$categoryDetails = Build-CategoryDetails -AppCount $appCount -TweakCount $tweakCount -DeploymentSettings @($config.Deployment)
|
||||
|
||||
$categories = Show-ImportExportConfigWindow -Owner $Owner -UsesDarkMode $UsesDarkMode -Title 'Import Configuration' -Prompt 'Select which settings to import:' -Categories $availableCategories -CategoryDetails $categoryDetails
|
||||
if (-not $categories) { return }
|
||||
$categories = Show-ImportExportConfigWindow -Owner $Owner -UsesDarkMode $UsesDarkMode -Title 'Import Configuration' -Prompt 'Select the settings you wish to import. You can review and modify them before they are applied.' -Categories $availableCategories -CategoryDetails $categoryDetails -ActionLabel 'Import Settings'
|
||||
if (-not $categories) {
|
||||
Write-Host 'Import canceled.'
|
||||
return
|
||||
}
|
||||
|
||||
if ($categories -contains 'Applications' -and $config.Apps) {
|
||||
$appIds = @(
|
||||
@@ -457,6 +489,7 @@ function Import-Configuration {
|
||||
Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
|
||||
)
|
||||
|
||||
Write-Host "Importing $($appIds.Count) app selection(s)."
|
||||
Apply-ImportedApplications -AppsPanel $AppsPanel -AppIds $appIds
|
||||
|
||||
if ($OnAppsImported) {
|
||||
@@ -464,12 +497,16 @@ function Import-Configuration {
|
||||
}
|
||||
}
|
||||
if ($categories -contains 'System Tweaks' -and $config.Tweaks) {
|
||||
$tweakCount = @($config.Tweaks).Count
|
||||
Write-Host "Importing $tweakCount tweak(s)."
|
||||
Apply-ImportedTweakSettings -Owner $Owner -UiControlMappings $UiControlMappings -TweakSettings @($config.Tweaks)
|
||||
}
|
||||
if ($categories -contains 'Deployment Settings' -and $config.Deployment) {
|
||||
Write-Host 'Importing deployment settings.'
|
||||
Apply-ImportedDeploymentSettings -Owner $Owner -UserSelectionCombo $UserSelectionCombo -OtherUsernameTextBox $OtherUsernameTextBox -DeploymentSettings @($config.Deployment)
|
||||
}
|
||||
|
||||
Write-Host 'Configuration imported successfully.'
|
||||
Show-MessageBox -Message "Configuration imported successfully." -Title 'Import Configuration' -Button 'OK' -Icon 'Information' | Out-Null
|
||||
|
||||
if ($OnImportCompleted) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@ function Show-MessageBox {
|
||||
[string]$Button = 'OK',
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[ValidateSet('None', 'Information', 'Warning', 'Error', 'Question')]
|
||||
[ValidateSet('None', 'Information', 'Success', 'Warning', 'Error', 'Question')]
|
||||
[string]$Icon = 'None',
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
@@ -90,6 +90,11 @@ function Show-MessageBox {
|
||||
$iconText.Foreground = $msgWindow.FindResource('InformationIconColor')
|
||||
$iconText.Visibility = 'Visible'
|
||||
}
|
||||
'Success' {
|
||||
$iconText.Text = [char]0xE73E
|
||||
$iconText.Foreground = $msgWindow.FindResource('SuccessIconColor')
|
||||
$iconText.Visibility = 'Visible'
|
||||
}
|
||||
'Warning' {
|
||||
$iconText.Text = [char]0xE7BA
|
||||
$iconText.Foreground = $msgWindow.FindResource('WarningIconColor')
|
||||
|
||||
431
Scripts/GUI/Show-RestoreBackupDialog.ps1
Normal file
431
Scripts/GUI/Show-RestoreBackupDialog.ps1
Normal file
@@ -0,0 +1,431 @@
|
||||
function Show-RestoreBackupDialog {
|
||||
param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[System.Windows.Window]$Owner = $null
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase | Out-Null
|
||||
|
||||
$usesDarkMode = GetSystemUsesDarkMode
|
||||
$ownerWindow = if ($Owner) { $Owner } else { $script:GuiWindow }
|
||||
|
||||
$overlay = $null
|
||||
$overlayWasAlreadyVisible = $false
|
||||
if ($ownerWindow) {
|
||||
try {
|
||||
$overlay = $ownerWindow.FindName('ModalOverlay')
|
||||
if ($overlay) {
|
||||
$overlayWasAlreadyVisible = ($overlay.Visibility -eq 'Visible')
|
||||
if (-not $overlayWasAlreadyVisible) {
|
||||
$ownerWindow.Dispatcher.Invoke([action]{ $overlay.Visibility = 'Visible' })
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
$schemaPath = $script:RestoreBackupWindowSchema
|
||||
if (-not $schemaPath -or -not (Test-Path $schemaPath)) {
|
||||
throw 'Restore backup window schema file could not be found.'
|
||||
}
|
||||
|
||||
$xaml = Get-Content -Path $schemaPath -Raw
|
||||
|
||||
$reader = [System.Xml.XmlReader]::Create([System.IO.StringReader]::new($xaml))
|
||||
try {
|
||||
$window = [System.Windows.Markup.XamlReader]::Load($reader)
|
||||
}
|
||||
finally {
|
||||
$reader.Close()
|
||||
}
|
||||
|
||||
if ($ownerWindow) {
|
||||
try {
|
||||
$window.Owner = $ownerWindow
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
try {
|
||||
SetWindowThemeResources -window $window -usesDarkMode $usesDarkMode
|
||||
}
|
||||
catch { }
|
||||
|
||||
$titleBar = $window.FindName('TitleBar')
|
||||
$titleText = $window.FindName('TitleText')
|
||||
$closeBtn = $window.FindName('CloseBtn')
|
||||
$backBtn = $window.FindName('BackBtn')
|
||||
$primaryActionBtn = $window.FindName('PrimaryActionBtn')
|
||||
$chooseRegistryBtn = $window.FindName('ChooseRegistryBtn')
|
||||
$chooseStartMenuBtn = $window.FindName('ChooseStartMenuBtn')
|
||||
$restoreModeTabs = $window.FindName('RestoreModeTabs')
|
||||
$startMenuIntroPanel = $window.FindName('StartMenuIntroPanel')
|
||||
$startMenuScopeCombo = $window.FindName('StartMenuScopeCombo')
|
||||
$startMenuAutoBackupCheck = $window.FindName('StartMenuAutoBackupCheck')
|
||||
$introInfoPanel = $window.FindName('IntroInfoPanel')
|
||||
$overviewPanel = $window.FindName('OverviewPanel')
|
||||
$overviewFeaturesSection = $window.FindName('OverviewFeaturesSection')
|
||||
$overviewSummaryText = $window.FindName('OverviewSummaryText')
|
||||
$backupFileText = $window.FindName('BackupFileText')
|
||||
$backupCreatedText = $window.FindName('BackupCreatedText')
|
||||
$backupTargetText = $window.FindName('BackupTargetText')
|
||||
$featuresItemsControl = $window.FindName('FeaturesItemsControl')
|
||||
$reappliedSeparator = $window.FindName('ReappliedSeparator')
|
||||
$reappliedPanel = $window.FindName('ReappliedPanel')
|
||||
$reappliedFeaturesItemsControl = $window.FindName('ReappliedFeaturesItemsControl')
|
||||
$nonRevertibleSeparator = $window.FindName('NonRevertibleSeparator')
|
||||
$nonRevertiblePanel = $window.FindName('NonRevertiblePanel')
|
||||
$nonRevertibleFeaturesItemsControl = $window.FindName('NonRevertibleFeaturesItemsControl')
|
||||
$nonRevertibleWikiLink = $window.FindName('NonRevertibleWikiLink')
|
||||
|
||||
$titleBar.Add_MouseLeftButtonDown({ $window.DragMove() })
|
||||
$window.Tag = New-RestoreDialogState
|
||||
$chooseRegistryBtn.IsDefault = $true
|
||||
|
||||
$state = @{ WizardStep = 'SelectType'; SelectedRegistryBackup = $null; SelectedStartMenuBackupFilePath = $null }
|
||||
|
||||
$getStartMenuScopeInfo = {
|
||||
$isAllUsersScope = ($startMenuScopeCombo.SelectedItem.Tag -eq 'AllUsers')
|
||||
$scopeValue = if ($isAllUsersScope) { 'AllUsers' } else { 'CurrentUser' }
|
||||
$summaryScopeText = if ($isAllUsersScope) { 'all users' } else { 'the current user' }
|
||||
|
||||
return [PSCustomObject]@{
|
||||
Scope = $scopeValue
|
||||
Target = $scopeValue
|
||||
SummaryText = $summaryScopeText
|
||||
}
|
||||
}
|
||||
|
||||
$showStartMenuIntroState = {
|
||||
$backupFileText.Text = 'Not selected'
|
||||
$backupCreatedText.Text = 'N/A'
|
||||
$overviewSummaryText.Visibility = 'Collapsed'
|
||||
$overviewPanel.Visibility = 'Collapsed'
|
||||
$startMenuIntroPanel.Visibility = 'Visible'
|
||||
$restoreModeTabs.SelectedIndex = 2
|
||||
}
|
||||
|
||||
$showStartMenuOverviewState = {
|
||||
param([string]$BackupFilePath)
|
||||
|
||||
$scopeInfo = & $getStartMenuScopeInfo
|
||||
$backupTargetText.Text = GetFriendlyRegistryBackupTarget -Target $scopeInfo.Target
|
||||
$overviewSummaryText.Text = "This will replace the current Start Menu pinned apps layout for $($scopeInfo.SummaryText) with the selected backup."
|
||||
$backupFileText.Text = Split-Path -Path $BackupFilePath -Leaf
|
||||
|
||||
$createdText = 'Unknown'
|
||||
try {
|
||||
$createdText = (Get-Item -LiteralPath $BackupFilePath -ErrorAction Stop).LastWriteTime.ToString('yyyy-MM-dd HH:mm')
|
||||
}
|
||||
catch { }
|
||||
$backupCreatedText.Text = $createdText
|
||||
|
||||
$overviewFeaturesSection.Visibility = 'Collapsed'
|
||||
$overviewSummaryText.Visibility = 'Visible'
|
||||
$reappliedSeparator.Visibility = 'Collapsed'
|
||||
$reappliedPanel.Visibility = 'Collapsed'
|
||||
$nonRevertibleSeparator.Visibility = 'Collapsed'
|
||||
$nonRevertiblePanel.Visibility = 'Collapsed'
|
||||
$introInfoPanel.Visibility = 'Collapsed'
|
||||
$overviewPanel.Visibility = 'Visible'
|
||||
$restoreModeTabs.SelectedIndex = 1
|
||||
}
|
||||
|
||||
$updateStartMenuOverviewPanel = {
|
||||
if ($state.WizardStep -ne 'StartMenu') {
|
||||
return
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($state.SelectedStartMenuBackupFilePath)) {
|
||||
& $showStartMenuIntroState
|
||||
return
|
||||
}
|
||||
|
||||
& $showStartMenuOverviewState $state.SelectedStartMenuBackupFilePath
|
||||
}
|
||||
|
||||
$updateStartMenuPrimaryActionText = {
|
||||
if ($state.WizardStep -ne 'StartMenu') {
|
||||
return
|
||||
}
|
||||
|
||||
$isAutoBackupEnabled = ($startMenuAutoBackupCheck.IsChecked -eq $true)
|
||||
$hasSelectedManualFile = -not [string]::IsNullOrWhiteSpace($state.SelectedStartMenuBackupFilePath)
|
||||
if ($isAutoBackupEnabled -or $hasSelectedManualFile) {
|
||||
$primaryActionBtn.Content = 'Restore backup'
|
||||
}
|
||||
else {
|
||||
$primaryActionBtn.Content = 'Select backup file'
|
||||
}
|
||||
}
|
||||
|
||||
$refreshStartMenuUi = {
|
||||
& $updateStartMenuOverviewPanel
|
||||
& $updateStartMenuPrimaryActionText
|
||||
}
|
||||
|
||||
$enterSelectTypeStep = {
|
||||
$titleText.Text = 'Restore Backup'
|
||||
$restoreModeTabs.SelectedIndex = 0
|
||||
$backBtn.Visibility = 'Visible'
|
||||
$backBtn.Content = 'Cancel'
|
||||
$primaryActionBtn.Visibility = 'Collapsed'
|
||||
$chooseRegistryBtn.IsDefault = $true
|
||||
$primaryActionBtn.IsDefault = $false
|
||||
}
|
||||
|
||||
$enterRegistryStep = {
|
||||
$titleText.Text = 'Restore Registry Backup'
|
||||
$restoreModeTabs.SelectedIndex = 1
|
||||
$introInfoPanel.Visibility = 'Visible'
|
||||
$overviewPanel.Visibility = 'Collapsed'
|
||||
$overviewFeaturesSection.Visibility = 'Visible'
|
||||
$overviewSummaryText.Visibility = 'Collapsed'
|
||||
$backBtn.Visibility = 'Visible'
|
||||
$backBtn.Content = 'Back'
|
||||
$primaryActionBtn.Visibility = 'Visible'
|
||||
$primaryActionBtn.Content = 'Select backup file'
|
||||
$primaryActionBtn.IsDefault = $true
|
||||
$chooseRegistryBtn.IsDefault = $false
|
||||
}
|
||||
|
||||
$enterStartMenuStep = {
|
||||
$titleText.Text = 'Restore Start Menu Backup'
|
||||
$restoreModeTabs.SelectedIndex = 2
|
||||
$backBtn.Visibility = 'Visible'
|
||||
$backBtn.Content = 'Back'
|
||||
$primaryActionBtn.Visibility = 'Visible'
|
||||
$primaryActionBtn.IsDefault = $true
|
||||
$chooseRegistryBtn.IsDefault = $false
|
||||
& $refreshStartMenuUi
|
||||
}
|
||||
|
||||
$showRegistryOverview = {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
$SelectedBackup,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$SelectedBackupFilePath
|
||||
)
|
||||
|
||||
$createdText = if ([string]::IsNullOrWhiteSpace($SelectedBackup.CreatedAt)) {
|
||||
'Unknown'
|
||||
}
|
||||
else {
|
||||
try {
|
||||
[DateTime]::Parse($SelectedBackup.CreatedAt).ToString('yyyy-MM-dd HH:mm')
|
||||
}
|
||||
catch {
|
||||
$SelectedBackup.CreatedAt
|
||||
}
|
||||
}
|
||||
|
||||
$selectedForwardFeatureIds = @(Get-SelectedForwardFeatureIdsFromBackup -SelectedBackup $SelectedBackup)
|
||||
$selectedUndoFeatureIds = @(Get-SelectedUndoFeatureIdsFromBackup -SelectedBackup $SelectedBackup)
|
||||
|
||||
$seenForwardFeatureIds = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||
foreach ($featureId in $selectedForwardFeatureIds) {
|
||||
[void]$seenForwardFeatureIds.Add([string]$featureId)
|
||||
}
|
||||
|
||||
$filteredUndoFeatureIds = New-Object System.Collections.Generic.List[string]
|
||||
foreach ($featureId in $selectedUndoFeatureIds) {
|
||||
if ($seenForwardFeatureIds.Contains([string]$featureId)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$filteredUndoFeatureIds.Add([string]$featureId)
|
||||
}
|
||||
|
||||
$forwardFeatureLists = Get-RestoreBackupFeatureLists -SelectedFeatureIds $selectedForwardFeatureIds -Features $script:Features
|
||||
$undoFeatureLists = Get-RestoreBackupFeatureLists -SelectedFeatureIds @($filteredUndoFeatureIds.ToArray()) -Features $script:Features
|
||||
$combinedFeatureLists = Get-RestoreBackupFeatureLists -SelectedFeatureIds (Get-SelectedFeatureIdsFromBackup -SelectedBackup $SelectedBackup) -Features $script:Features
|
||||
|
||||
$revertibleFeaturesList = @($forwardFeatureLists.Revertible)
|
||||
$reappliedFeaturesList = @($undoFeatureLists.Revertible)
|
||||
$nonRevertibleFeaturesList = @($combinedFeatureLists.NonRevertible)
|
||||
Write-Host "Backup overview prepared. Reverted=$($revertibleFeaturesList.Count), ReApplied=$($reappliedFeaturesList.Count), NonRevertible=$($nonRevertibleFeaturesList.Count)"
|
||||
|
||||
if ($revertibleFeaturesList.Count -eq 0 -and $reappliedFeaturesList.Count -eq 0) {
|
||||
throw 'The selected backup does not contain any changes that can be restored.'
|
||||
}
|
||||
|
||||
$backupFileText.Text = Split-Path $SelectedBackupFilePath -Leaf
|
||||
$backupCreatedText.Text = $createdText
|
||||
$backupTargetText.Text = GetFriendlyRegistryBackupTarget -Target ([string]$SelectedBackup.Target)
|
||||
$featuresItemsControl.ItemsSource = $revertibleFeaturesList
|
||||
$overviewFeaturesSection.Visibility = if ($revertibleFeaturesList.Count -gt 0) { 'Visible' } else { 'Collapsed' }
|
||||
$reappliedFeaturesItemsControl.ItemsSource = $reappliedFeaturesList
|
||||
if ($reappliedFeaturesList.Count -gt 0) { $reappliedPanel.Visibility = 'Visible' } else { $reappliedPanel.Visibility = 'Collapsed' }
|
||||
if ($revertibleFeaturesList.Count -gt 0 -and $reappliedFeaturesList.Count -gt 0) { $reappliedSeparator.Visibility = 'Visible' } else { $reappliedSeparator.Visibility = 'Collapsed' }
|
||||
$overviewSummaryText.Visibility = 'Collapsed'
|
||||
$nonRevertibleFeaturesItemsControl.ItemsSource = $nonRevertibleFeaturesList
|
||||
|
||||
$hasNonRevertibleItems = ($nonRevertibleFeaturesList.Count -gt 0)
|
||||
if ($hasNonRevertibleItems) { $nonRevertiblePanel.Visibility = 'Visible' } else { $nonRevertiblePanel.Visibility = 'Collapsed' }
|
||||
if ($hasNonRevertibleItems -and ($revertibleFeaturesList.Count -gt 0 -or $reappliedFeaturesList.Count -gt 0)) { $nonRevertibleSeparator.Visibility = 'Visible' } else { $nonRevertibleSeparator.Visibility = 'Collapsed' }
|
||||
$introInfoPanel.Visibility = 'Collapsed'
|
||||
$overviewPanel.Visibility = 'Visible'
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
$handleRegistryPrimaryAction = {
|
||||
if ($state.SelectedRegistryBackup) {
|
||||
$window.Tag = @{
|
||||
Result = 'RestoreRegistry'
|
||||
Backup = $state.SelectedRegistryBackup
|
||||
}
|
||||
$window.DialogResult = $true
|
||||
$window.Close()
|
||||
return
|
||||
}
|
||||
|
||||
$openDialog = New-Object Microsoft.Win32.OpenFileDialog
|
||||
$openDialog.Title = 'Select Registry Backup File'
|
||||
$openDialog.Filter = 'Registry backup (*.json)|*.json'
|
||||
$openDialog.DefaultExt = '.json'
|
||||
$openDialog.InitialDirectory = $script:RegistryBackupsPath
|
||||
|
||||
if ($openDialog.ShowDialog($window) -ne $true) {
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "Backup file selected: $($openDialog.FileName)"
|
||||
$selectedBackup = Load-RegistryBackupFromFile -FilePath $openDialog.FileName
|
||||
|
||||
if (-not (& $showRegistryOverview -SelectedBackup $selectedBackup -SelectedBackupFilePath $openDialog.FileName)) {
|
||||
return
|
||||
}
|
||||
|
||||
$state.SelectedRegistryBackup = $selectedBackup
|
||||
$primaryActionBtn.Content = 'Restore from backup'
|
||||
}
|
||||
|
||||
$handleStartMenuPrimaryAction = {
|
||||
$scope = (& $getStartMenuScopeInfo).Scope
|
||||
$useManualBackupFile = -not ($startMenuAutoBackupCheck.IsChecked -eq $true)
|
||||
|
||||
if ($useManualBackupFile -and [string]::IsNullOrWhiteSpace($state.SelectedStartMenuBackupFilePath)) {
|
||||
$openDialog = New-Object Microsoft.Win32.OpenFileDialog
|
||||
$openDialog.Title = 'Select Start Menu Backup File'
|
||||
$openDialog.Filter = 'Start Menu backup (*.bak)|*.bak'
|
||||
$openDialog.InitialDirectory = "$env:LOCALAPPDATA\Packages\Microsoft.Windows.StartMenuExperienceHost_cw5n1h2txyewy\LocalState"
|
||||
$openDialog.DefaultExt = '.bak'
|
||||
|
||||
if ($openDialog.ShowDialog($window) -ne $true) {
|
||||
return
|
||||
}
|
||||
|
||||
$state.SelectedStartMenuBackupFilePath = $openDialog.FileName
|
||||
Write-Host "Selected Start Menu backup file: $($state.SelectedStartMenuBackupFilePath)"
|
||||
& $refreshStartMenuUi
|
||||
return
|
||||
}
|
||||
|
||||
$window.Tag = @{
|
||||
Result = 'RestoreStartMenu'
|
||||
StartMenuScope = $scope
|
||||
UseManualBackupFile = $useManualBackupFile
|
||||
BackupFilePath = $state.SelectedStartMenuBackupFilePath
|
||||
}
|
||||
$window.DialogResult = $true
|
||||
$window.Close()
|
||||
}
|
||||
|
||||
$setWizardStep = {
|
||||
param([string]$step)
|
||||
|
||||
$state.WizardStep = $step
|
||||
|
||||
switch ($step) {
|
||||
'SelectType' { & $enterSelectTypeStep }
|
||||
'Registry' { & $enterRegistryStep }
|
||||
'StartMenu' { & $enterStartMenuStep }
|
||||
}
|
||||
}
|
||||
|
||||
$startMenuAutoBackupCheck.Add_Checked({
|
||||
$state.SelectedStartMenuBackupFilePath = $null
|
||||
& $refreshStartMenuUi
|
||||
})
|
||||
$startMenuAutoBackupCheck.Add_Unchecked({
|
||||
& $refreshStartMenuUi
|
||||
})
|
||||
|
||||
$startMenuScopeCombo.Add_SelectionChanged({
|
||||
& $refreshStartMenuUi
|
||||
})
|
||||
|
||||
$nonRevertibleWikiLink.Add_MouseLeftButtonUp({
|
||||
try {
|
||||
Start-Process 'https://github.com/Raphire/Win11Debloat/wiki/Reverting-Changes' | Out-Null
|
||||
}
|
||||
catch { }
|
||||
})
|
||||
|
||||
$closeBtn.Add_Click({
|
||||
$window.Tag = New-RestoreDialogState
|
||||
$window.DialogResult = $false
|
||||
$window.Close()
|
||||
})
|
||||
|
||||
$chooseRegistryBtn.Add_Click({ & $setWizardStep 'Registry' })
|
||||
$chooseStartMenuBtn.Add_Click({ & $setWizardStep 'StartMenu' })
|
||||
|
||||
$backBtn.Add_Click({
|
||||
if ($state.WizardStep -eq 'SelectType') {
|
||||
$window.Tag = New-RestoreDialogState
|
||||
$window.DialogResult = $false
|
||||
$window.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if ($state.WizardStep -eq 'Registry') {
|
||||
$state.SelectedRegistryBackup = $null
|
||||
}
|
||||
|
||||
if ($state.WizardStep -eq 'StartMenu') {
|
||||
$state.SelectedStartMenuBackupFilePath = $null
|
||||
$startMenuAutoBackupCheck.IsChecked = $true
|
||||
}
|
||||
|
||||
& $setWizardStep 'SelectType'
|
||||
})
|
||||
|
||||
$primaryActionBtn.Add_Click({
|
||||
switch ($state.WizardStep) {
|
||||
'Registry' { & $handleRegistryPrimaryAction }
|
||||
'StartMenu' { & $handleStartMenuPrimaryAction }
|
||||
}
|
||||
})
|
||||
|
||||
$window.Add_KeyDown({
|
||||
param($source, $e)
|
||||
if ($e.Key -eq 'Escape') {
|
||||
$window.Tag = New-RestoreDialogState
|
||||
$window.DialogResult = $false
|
||||
$window.Close()
|
||||
}
|
||||
})
|
||||
|
||||
& $setWizardStep 'SelectType'
|
||||
|
||||
try {
|
||||
$null = $window.ShowDialog()
|
||||
}
|
||||
catch {
|
||||
$innerMessage = if ($_.Exception.InnerException) { $_.Exception.InnerException.Message } else { 'None' }
|
||||
throw "Failed to show restore backup dialog. Error: $($_.Exception.Message) Inner: $innerMessage"
|
||||
}
|
||||
finally {
|
||||
if ($overlay -and -not $overlayWasAlreadyVisible) {
|
||||
try {
|
||||
$ownerWindow.Dispatcher.Invoke([action]{ $overlay.Visibility = 'Collapsed' })
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
return $window.Tag
|
||||
}
|
||||
102
Scripts/GUI/Show-RestoreBackupWindow.ps1
Normal file
102
Scripts/GUI/Show-RestoreBackupWindow.ps1
Normal file
@@ -0,0 +1,102 @@
|
||||
function Show-RestoreBackupWindow {
|
||||
param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[System.Windows.Window]$Owner = $null
|
||||
)
|
||||
|
||||
try {
|
||||
Write-Host 'Opening restore backup dialog.'
|
||||
|
||||
$restoreResult = [PSCustomObject]@{
|
||||
RestoredRegistry = $false
|
||||
RestoredStartMenu = $false
|
||||
}
|
||||
|
||||
$dialogResult = Show-RestoreBackupDialog -Owner $Owner
|
||||
if (-not $dialogResult -or $dialogResult.Result -eq 'Cancel') {
|
||||
Write-Host 'Restore canceled by user.'
|
||||
return $restoreResult
|
||||
}
|
||||
|
||||
$successMessage = $null
|
||||
$warningMessage = $null
|
||||
|
||||
if ($dialogResult.Result -eq 'RestoreRegistry') {
|
||||
$backup = $dialogResult.Backup
|
||||
if (-not $backup) {
|
||||
throw 'Registry backup restore requested without a selected backup.'
|
||||
}
|
||||
|
||||
Write-Host "User confirmed registry restore for $($backup.Target)."
|
||||
Restore-RegistryBackupState -Backup $backup
|
||||
$restoreResult.RestoredRegistry = $true
|
||||
$successMessage = 'Registry backup restored successfully. Some changes may require a restart to take effect.'
|
||||
}
|
||||
elseif ($dialogResult.Result -eq 'RestoreStartMenu') {
|
||||
$scope = $dialogResult.StartMenuScope
|
||||
$useManualBackupFile = ($dialogResult.UseManualBackupFile -eq $true)
|
||||
$backupFilePath = $null
|
||||
if ($dialogResult -is [hashtable] -and $dialogResult.ContainsKey('BackupFilePath')) {
|
||||
$backupFilePath = $dialogResult['BackupFilePath']
|
||||
}
|
||||
elseif ($dialogResult.PSObject.Properties.Match('BackupFilePath').Count -gt 0) {
|
||||
$backupFilePath = $dialogResult.BackupFilePath
|
||||
}
|
||||
|
||||
if ($useManualBackupFile -and [string]::IsNullOrWhiteSpace($backupFilePath)) {
|
||||
throw 'Start Menu restore canceled: no backup file selected.'
|
||||
}
|
||||
|
||||
$result = if ($scope -eq 'AllUsers') {
|
||||
RestoreStartMenuForAllUsers -BackupFilePath $backupFilePath
|
||||
}
|
||||
else {
|
||||
RestoreStartMenu -BackupFilePath $backupFilePath
|
||||
}
|
||||
|
||||
$resultEntries = @($result)
|
||||
$successCount = @($resultEntries | Where-Object { $_.Result -eq $true }).Count
|
||||
$failedEntries = @($resultEntries | Where-Object { $_.Result -ne $true })
|
||||
|
||||
if ($successCount -eq 0) {
|
||||
$errorSummary = ($resultEntries | ForEach-Object { $_.Message }) -join [Environment]::NewLine
|
||||
throw "Failed to restore the Start Menu backup.`n$errorSummary"
|
||||
}
|
||||
|
||||
if ($failedEntries.Count -gt 0) {
|
||||
$failureSummary = ($failedEntries | ForEach-Object { $_.Message }) -join [Environment]::NewLine
|
||||
$warningMessage = "The Start Menu backup was successfully restored for $successCount user(s).`nSome users could not be restored:`n$failureSummary"
|
||||
}
|
||||
else {
|
||||
if ($scope -eq 'AllUsers') {
|
||||
$successMessage = "The Start Menu backup was successfully restored for all users. The changes will apply the next time users sign in."
|
||||
}
|
||||
else {
|
||||
$successMessage = "The Start Menu backup was successfully restored for the current user. The changes will apply the next time you sign in."
|
||||
}
|
||||
}
|
||||
|
||||
$restoreResult.RestoredStartMenu = $true
|
||||
}
|
||||
|
||||
if ($warningMessage) {
|
||||
Write-Host "$warningMessage"
|
||||
Show-MessageBox -Title 'Backup Restored' -Message $warningMessage -Icon Warning
|
||||
}
|
||||
elseif ($successMessage) {
|
||||
Write-Host "$successMessage"
|
||||
Show-MessageBox -Title 'Backup Restored' -Message $successMessage -Icon Success
|
||||
}
|
||||
|
||||
return $restoreResult
|
||||
}
|
||||
catch {
|
||||
$errorMessage = if ($_.Exception.Message) { $_.Exception.Message } else { 'An unexpected error occurred.' }
|
||||
Write-Error "Restore operation failed: $errorMessage"
|
||||
Show-MessageBox -Title 'Error' -Message "Restore failed: $errorMessage" -Icon Error
|
||||
return [PSCustomObject]@{
|
||||
RestoredRegistry = $false
|
||||
RestoredStartMenu = $false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
function Show-RevertSettingsModal {
|
||||
param (
|
||||
[Parameter(Mandatory=$false)]
|
||||
[System.Windows.Window]$Owner = $null,
|
||||
[Parameter(Mandatory=$true)]
|
||||
$LastUsedSettings
|
||||
)
|
||||
|
||||
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase | Out-Null
|
||||
|
||||
$usesDarkMode = GetSystemUsesDarkMode
|
||||
|
||||
# Determine owner window
|
||||
$ownerWindow = if ($Owner) { $Owner } else { $script:GuiWindow }
|
||||
|
||||
# Show overlay if owner window exists
|
||||
$overlay = $null
|
||||
$overlayWasAlreadyVisible = $false
|
||||
if ($ownerWindow) {
|
||||
try {
|
||||
$overlay = $ownerWindow.FindName('ModalOverlay')
|
||||
if ($overlay) {
|
||||
$overlayWasAlreadyVisible = ($overlay.Visibility -eq 'Visible')
|
||||
if (-not $overlayWasAlreadyVisible) {
|
||||
$ownerWindow.Dispatcher.Invoke([action]{ $overlay.Visibility = 'Visible' })
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
# Load XAML from file
|
||||
$xaml = Get-Content -Path $script:RevertSettingsWindowSchema -Raw
|
||||
$reader = [System.Xml.XmlReader]::Create([System.IO.StringReader]::new($xaml))
|
||||
try {
|
||||
$revertWindow = [System.Windows.Markup.XamlReader]::Load($reader)
|
||||
}
|
||||
finally {
|
||||
$reader.Close()
|
||||
}
|
||||
|
||||
if ($ownerWindow) {
|
||||
try {
|
||||
$revertWindow.Owner = $ownerWindow
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
SetWindowThemeResources -window $revertWindow -usesDarkMode $usesDarkMode
|
||||
|
||||
$itemsPanel = $revertWindow.FindName('RevertItemsPanel')
|
||||
$countText = $revertWindow.FindName('RevertSelectionCount')
|
||||
$selectAllBtn = $revertWindow.FindName('RevertSelectAllBtn')
|
||||
$clearBtn = $revertWindow.FindName('RevertClearBtn')
|
||||
$applyBtn = $revertWindow.FindName('RevertApplyBtn')
|
||||
$cancelBtn = $revertWindow.FindName('RevertCancelBtn')
|
||||
$restartExplorerCheckbox = $revertWindow.FindName('RevertRestartExplorerCheckBox')
|
||||
$featureCheckboxStyle = $revertWindow.FindResource('FeatureCheckboxStyle')
|
||||
$restartExplorerCheckbox.Style = $featureCheckboxStyle
|
||||
$entryCheckboxes = @()
|
||||
|
||||
foreach ($setting in $LastUsedSettings.Settings) {
|
||||
if ($setting.Value -ne $true) { continue }
|
||||
if ($setting.Name -eq 'Apps' -or $setting.Name -eq 'RemoveApps' -or $setting.Name -eq 'CreateRestorePoint') { continue }
|
||||
|
||||
$feature = $null
|
||||
if ($script:Features.ContainsKey($setting.Name)) {
|
||||
$feature = $script:Features[$setting.Name]
|
||||
}
|
||||
$undoFeature = GetUndoFeatureForParam -paramKey $setting.Name
|
||||
|
||||
$label = $setting.Name
|
||||
if ($feature -and $feature.Action) {
|
||||
$label = $feature.Action
|
||||
}
|
||||
|
||||
$undoLabel = if ($undoFeature -and $undoFeature.UndoAction) {
|
||||
$undoFeature.UndoAction
|
||||
} else {
|
||||
'No revert action available'
|
||||
}
|
||||
|
||||
$canUndo = ($null -ne $undoFeature)
|
||||
|
||||
$itemBorder = New-Object System.Windows.Controls.Border
|
||||
$itemBorder.Style = $revertWindow.FindResource('RevertItemBorderStyle')
|
||||
|
||||
$row = New-Object System.Windows.Controls.StackPanel
|
||||
$row.Style = $revertWindow.FindResource('RevertItemRowStyle')
|
||||
|
||||
$checkbox = New-Object System.Windows.Controls.CheckBox
|
||||
$checkbox.Content = $label
|
||||
$checkbox.Tag = $setting.Name
|
||||
$checkbox.Style = $featureCheckboxStyle
|
||||
$checkbox.IsEnabled = $canUndo
|
||||
|
||||
$undoText = New-Object System.Windows.Controls.TextBlock
|
||||
$undoText.Text = if ($canUndo) { "Revert to: $undoLabel" } else { 'Revert not supported for this setting' }
|
||||
$undoText.Style = $revertWindow.FindResource('RevertItemUndoTextStyle')
|
||||
$undoText.Opacity = if ($canUndo) { 0.75 } else { 0.4 }
|
||||
|
||||
$row.Children.Add($checkbox) | Out-Null
|
||||
$row.Children.Add($undoText) | Out-Null
|
||||
$itemBorder.Child = $row
|
||||
|
||||
$itemsPanel.Children.Add($itemBorder) | Out-Null
|
||||
$entryCheckboxes += $checkbox
|
||||
}
|
||||
|
||||
# Remove the divider from the last entry for cleaner list termination.
|
||||
if ($itemsPanel.Children.Count -gt 0) {
|
||||
$lastItem = $itemsPanel.Children[$itemsPanel.Children.Count - 1]
|
||||
if ($lastItem -is [System.Windows.Controls.Border]) {
|
||||
$lastItem.BorderThickness = [System.Windows.Thickness]::new(0)
|
||||
}
|
||||
}
|
||||
|
||||
if ($entryCheckboxes.Count -eq 0) {
|
||||
$emptyText = New-Object System.Windows.Controls.TextBlock
|
||||
$emptyText.Text = 'No previously applied tweaks can be reverted'
|
||||
$emptyText.Style = $revertWindow.FindResource('RevertEmptyTextStyle')
|
||||
$itemsPanel.Children.Add($emptyText) | Out-Null
|
||||
$selectAllBtn.IsEnabled = $false
|
||||
$clearBtn.IsEnabled = $false
|
||||
}
|
||||
|
||||
$updateState = {
|
||||
$selectedCount = 0
|
||||
foreach ($cb in $entryCheckboxes) {
|
||||
if ($cb.IsEnabled -and $cb.IsChecked -eq $true) {
|
||||
$selectedCount++
|
||||
}
|
||||
}
|
||||
|
||||
$countText.Text = "$selectedCount settings selected"
|
||||
$applyBtn.IsEnabled = ($selectedCount -gt 0)
|
||||
}
|
||||
|
||||
foreach ($cb in $entryCheckboxes) {
|
||||
$cb.Add_Checked($updateState)
|
||||
$cb.Add_Unchecked($updateState)
|
||||
}
|
||||
|
||||
$selectAllBtn.Add_Click({
|
||||
foreach ($cb in $entryCheckboxes) {
|
||||
if ($cb.IsEnabled) {
|
||||
$cb.IsChecked = $true
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
$clearBtn.Add_Click({
|
||||
foreach ($cb in $entryCheckboxes) {
|
||||
if ($cb.IsEnabled) {
|
||||
$cb.IsChecked = $false
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
$cancelHandler = {
|
||||
$revertWindow.Close()
|
||||
}
|
||||
|
||||
$cancelBtn.Add_Click($cancelHandler)
|
||||
|
||||
$applyBtn.Add_Click({
|
||||
$selected = @()
|
||||
foreach ($cb in $entryCheckboxes) {
|
||||
if ($cb.IsEnabled -and $cb.IsChecked -eq $true -and $cb.Tag) {
|
||||
$selected += $cb.Tag
|
||||
}
|
||||
}
|
||||
|
||||
$revertWindow.Tag = [PSCustomObject]@{
|
||||
SelectedFeatureIds = $selected
|
||||
RestartExplorer = ($restartExplorerCheckbox -and $restartExplorerCheckbox.IsChecked -eq $true)
|
||||
}
|
||||
$revertWindow.Close()
|
||||
})
|
||||
|
||||
$revertWindow.ShowDialog() | Out-Null
|
||||
|
||||
if ($overlay -and -not $overlayWasAlreadyVisible) {
|
||||
try {
|
||||
$ownerWindow.Dispatcher.Invoke([action]{ $overlay.Visibility = 'Collapsed' })
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
if ($revertWindow.Tag) {
|
||||
return $revertWindow.Tag
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
SelectedFeatureIds = @()
|
||||
RestartExplorer = $false
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,7 @@ param (
|
||||
[switch]$RemoveApps,
|
||||
[switch]$RemoveAppsCustom,
|
||||
[switch]$RemoveGamingApps,
|
||||
[switch]$RemoveCommApps,
|
||||
[switch]$RemoveHPApps,
|
||||
[switch]$RemoveW11Outlook,
|
||||
[switch]$ForceRemoveEdge,
|
||||
[switch]$DisableDVR,
|
||||
[switch]$DisableGameBarIntegration,
|
||||
@@ -58,7 +56,7 @@ param (
|
||||
[switch]$HideSearchTb, [switch]$ShowSearchIconTb, [switch]$ShowSearchLabelTb, [switch]$ShowSearchBoxTb,
|
||||
[switch]$HideTaskview,
|
||||
[switch]$DisableStartRecommended,
|
||||
[switch]$DisableStartAllApps,
|
||||
[switch]$DisableStartAllApps, [switch]$StartAllAppsCategory, [switch]$StartAllAppsGrid, [switch]$StartAllAppsList,
|
||||
[switch]$DisableStartPhoneLink,
|
||||
[switch]$DisableCopilot,
|
||||
[switch]$DisableRecall,
|
||||
@@ -117,11 +115,15 @@ Write-Output "------------------------------------------------------------------
|
||||
Write-Output " Win11Debloat Script - Get Dev"
|
||||
Write-Output "-------------------------------------------------------------------------------------------"
|
||||
|
||||
$tempRootPath = $env:TEMP
|
||||
$tempWorkPath = Join-Path $tempRootPath 'Win11Debloat'
|
||||
$tempArchivePath = Join-Path $tempRootPath 'win11debloat.zip'
|
||||
|
||||
Write-Output "> Downloading Win11Debloat for development..."
|
||||
|
||||
# Download latest version of Win11Debloat from GitHub master branch as zip archive
|
||||
try {
|
||||
Invoke-RestMethod "https://github.com/Raphire/Win11Debloat/archive/refs/heads/master.zip" -OutFile "$env:TEMP/win11debloat.zip"
|
||||
Invoke-RestMethod "https://github.com/Raphire/Win11Debloat/archive/refs/heads/master.zip" -OutFile $tempArchivePath
|
||||
}
|
||||
catch {
|
||||
Write-Host "Error: Unable to fetch master branch from GitHub. Please check your internet connection and try again." -ForegroundColor Red
|
||||
@@ -131,19 +133,22 @@ catch {
|
||||
Exit
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
Write-Output "> Cleaning up old Win11Debloat folder..."
|
||||
# Remove old script folder if it exists, but keep configs, logs and backups
|
||||
if (Test-Path $tempWorkPath) {
|
||||
Write-Output ""
|
||||
Write-Output "> Cleaning up old Win11Debloat folder..."
|
||||
|
||||
# Remove old script folder if it exists, but keep config and log files
|
||||
if (Test-Path "$env:TEMP/Win11Debloat") {
|
||||
Get-ChildItem -Path "$env:TEMP/Win11Debloat" -Exclude CustomAppsList,LastUsedSettings.json,Win11Debloat.log,Config,Logs | Remove-Item -Recurse -Force
|
||||
Get-ChildItem -Path $tempWorkPath -Exclude Config,Logs,Backups | Remove-Item -Recurse -Force
|
||||
}
|
||||
|
||||
$configDir = "$env:TEMP/Win11Debloat/Config"
|
||||
$backupDir = "$env:TEMP/Win11Debloat/ConfigOld"
|
||||
$configDir = Join-Path $tempWorkPath 'Config'
|
||||
$backupDir = Join-Path $tempWorkPath 'ConfigOld'
|
||||
|
||||
# Temporarily move existing config files if they exist to prevent them from being overwritten by the new script files, will be moved back after the new script is unpacked
|
||||
if (Test-Path "$configDir") {
|
||||
Write-Output ""
|
||||
Write-Output "> Backing up existing config files..."
|
||||
|
||||
New-Item -ItemType Directory -Path "$backupDir" -Force | Out-Null
|
||||
|
||||
$filesToKeep = @(
|
||||
@@ -160,13 +165,13 @@ Write-Output ""
|
||||
Write-Output "> Unpacking..."
|
||||
|
||||
# Unzip archive to Win11Debloat folder
|
||||
Expand-Archive "$env:TEMP/win11debloat.zip" "$env:TEMP/Win11Debloat"
|
||||
Expand-Archive $tempArchivePath $tempWorkPath
|
||||
|
||||
# Remove archive
|
||||
Remove-Item "$env:TEMP/win11debloat.zip"
|
||||
Remove-Item $tempArchivePath
|
||||
|
||||
# Move files
|
||||
Get-ChildItem -Path "$env:TEMP/Win11Debloat/*Win11Debloat-*" -Recurse | Move-Item -Destination "$env:TEMP/Win11Debloat"
|
||||
Get-ChildItem -Path (Join-Path $tempWorkPath '*Win11Debloat-*') -Recurse | Move-Item -Destination $tempWorkPath
|
||||
|
||||
# Add existing config files back to Config folder
|
||||
if (Test-Path "$backupDir") {
|
||||
@@ -174,6 +179,9 @@ if (Test-Path "$backupDir") {
|
||||
New-Item -ItemType Directory -Path "$configDir" -Force | Out-Null
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
Write-Output "> Restoring existing config files..."
|
||||
|
||||
Get-ChildItem -Path "$backupDir" -Recurse | Move-Item -Destination "$configDir"
|
||||
Remove-Item "$backupDir" -Recurse -Force
|
||||
}
|
||||
@@ -206,20 +214,21 @@ if ($PSVersionTable.PSVersion.Major -ge 7) {
|
||||
}
|
||||
|
||||
# Run Win11Debloat script with the provided arguments
|
||||
$debloatProcess = Start-Process powershell.exe -WindowStyle $windowStyle -PassThru -ArgumentList "-executionpolicy bypass -File $env:TEMP\Win11Debloat\Win11Debloat.ps1 $arguments" -Verb RunAs
|
||||
$debloatScriptPath = Join-Path $tempWorkPath 'Win11Debloat.ps1'
|
||||
$debloatProcess = Start-Process powershell.exe -WindowStyle $windowStyle -PassThru -ArgumentList "-executionpolicy bypass -File `"$debloatScriptPath`" $arguments" -Verb RunAs
|
||||
|
||||
# Wait for the process to finish before continuing
|
||||
if ($null -ne $debloatProcess) {
|
||||
$debloatProcess.WaitForExit()
|
||||
}
|
||||
|
||||
# Remove all remaining script files, except for CustomAppsList and LastUsedSettings.json files
|
||||
if (Test-Path "$env:TEMP/Win11Debloat") {
|
||||
# Remove all remaining script files, except for configs, logs and backups
|
||||
if (Test-Path $tempWorkPath) {
|
||||
Write-Output ""
|
||||
Write-Output "> Cleaning up..."
|
||||
|
||||
# Cleanup, remove Win11Debloat directory
|
||||
Get-ChildItem -Path "$env:TEMP/Win11Debloat" -Exclude CustomAppsList,LastUsedSettings.json,Win11Debloat.log,Win11Debloat-Run.log,Config,Logs | Remove-Item -Recurse -Force
|
||||
Get-ChildItem -Path $tempWorkPath -Exclude Config,Logs,Backups | Remove-Item -Recurse -Force
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
param (
|
||||
[switch]$CLI,
|
||||
[switch]$Silent,
|
||||
[switch]$Undo,
|
||||
[switch]$Verbose,
|
||||
[switch]$Sysprep,
|
||||
[string]$LogPath,
|
||||
@@ -18,9 +17,7 @@ param (
|
||||
[switch]$RemoveApps,
|
||||
[switch]$RemoveAppsCustom,
|
||||
[switch]$RemoveGamingApps,
|
||||
[switch]$RemoveCommApps,
|
||||
[switch]$RemoveHPApps,
|
||||
[switch]$RemoveW11Outlook,
|
||||
[switch]$ForceRemoveEdge,
|
||||
[switch]$DisableDVR,
|
||||
[switch]$DisableGameBarIntegration,
|
||||
@@ -59,7 +56,7 @@ param (
|
||||
[switch]$HideSearchTb, [switch]$ShowSearchIconTb, [switch]$ShowSearchLabelTb, [switch]$ShowSearchBoxTb,
|
||||
[switch]$HideTaskview,
|
||||
[switch]$DisableStartRecommended,
|
||||
[switch]$DisableStartAllApps,
|
||||
[switch]$DisableStartAllApps, [switch]$StartAllAppsCategory, [switch]$StartAllAppsGrid, [switch]$StartAllAppsList,
|
||||
[switch]$DisableStartPhoneLink,
|
||||
[switch]$DisableCopilot,
|
||||
[switch]$DisableRecall,
|
||||
@@ -118,12 +115,16 @@ Write-Output "------------------------------------------------------------------
|
||||
Write-Output " Win11Debloat Script - Get"
|
||||
Write-Output "-------------------------------------------------------------------------------------------"
|
||||
|
||||
$tempRootPath = $env:TEMP
|
||||
$tempWorkPath = Join-Path $tempRootPath 'Win11Debloat'
|
||||
$tempArchivePath = Join-Path $tempRootPath 'win11debloat.zip'
|
||||
|
||||
Write-Output "> Downloading Win11Debloat..."
|
||||
|
||||
# Download latest version of Win11Debloat from GitHub as zip archive
|
||||
try {
|
||||
$LatestReleaseUri = (Invoke-RestMethod https://api.github.com/repos/Raphire/Win11Debloat/releases/latest).zipball_url
|
||||
Invoke-RestMethod $LatestReleaseUri -OutFile "$env:TEMP/win11debloat.zip"
|
||||
Invoke-RestMethod $LatestReleaseUri -OutFile $tempArchivePath
|
||||
}
|
||||
catch {
|
||||
Write-Host "Error: Unable to fetch latest release from GitHub. Please check your internet connection and try again." -ForegroundColor Red
|
||||
@@ -133,19 +134,22 @@ catch {
|
||||
Exit
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
Write-Output "> Cleaning up old Win11Debloat folder..."
|
||||
# Remove old script folder if it exists, but keep configs, logs and backups
|
||||
if (Test-Path $tempWorkPath) {
|
||||
Write-Output ""
|
||||
Write-Output "> Cleaning up old Win11Debloat folder..."
|
||||
|
||||
# Remove old script folder if it exists, but keep config and log files
|
||||
if (Test-Path "$env:TEMP/Win11Debloat") {
|
||||
Get-ChildItem -Path "$env:TEMP/Win11Debloat" -Exclude CustomAppsList,LastUsedSettings.json,Win11Debloat.log,Config,Logs | Remove-Item -Recurse -Force
|
||||
Get-ChildItem -Path $tempWorkPath -Exclude Config,Logs,Backups | Remove-Item -Recurse -Force
|
||||
}
|
||||
|
||||
$configDir = "$env:TEMP/Win11Debloat/Config"
|
||||
$backupDir = "$env:TEMP/Win11Debloat/ConfigOld"
|
||||
$configDir = Join-Path $tempWorkPath 'Config'
|
||||
$backupDir = Join-Path $tempWorkPath 'ConfigOld'
|
||||
|
||||
# Temporarily move existing config files if they exist to prevent them from being overwritten by the new script files, will be moved back after the new script is unpacked
|
||||
if (Test-Path "$configDir") {
|
||||
Write-Output ""
|
||||
Write-Output "> Backing up existing config files..."
|
||||
|
||||
New-Item -ItemType Directory -Path "$backupDir" -Force | Out-Null
|
||||
|
||||
$filesToKeep = @(
|
||||
@@ -162,13 +166,13 @@ Write-Output ""
|
||||
Write-Output "> Unpacking..."
|
||||
|
||||
# Unzip archive to Win11Debloat folder
|
||||
Expand-Archive "$env:TEMP/win11debloat.zip" "$env:TEMP/Win11Debloat"
|
||||
Expand-Archive $tempArchivePath $tempWorkPath
|
||||
|
||||
# Remove archive
|
||||
Remove-Item "$env:TEMP/win11debloat.zip"
|
||||
Remove-Item $tempArchivePath
|
||||
|
||||
# Move files
|
||||
Get-ChildItem -Path "$env:TEMP/Win11Debloat/Raphire-Win11Debloat-*" -Recurse | Move-Item -Destination "$env:TEMP/Win11Debloat"
|
||||
Get-ChildItem -Path (Join-Path $tempWorkPath '*Win11Debloat-*') -Recurse | Move-Item -Destination $tempWorkPath
|
||||
|
||||
# Add existing config files back to Config folder
|
||||
if (Test-Path "$backupDir") {
|
||||
@@ -176,6 +180,9 @@ if (Test-Path "$backupDir") {
|
||||
New-Item -ItemType Directory -Path "$configDir" -Force | Out-Null
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
Write-Output "> Restoring existing config files..."
|
||||
|
||||
Get-ChildItem -Path "$backupDir" -Recurse | Move-Item -Destination "$configDir"
|
||||
Remove-Item "$backupDir" -Recurse -Force
|
||||
}
|
||||
@@ -208,20 +215,21 @@ if ($PSVersionTable.PSVersion.Major -ge 7) {
|
||||
}
|
||||
|
||||
# Run Win11Debloat script with the provided arguments
|
||||
$debloatProcess = Start-Process powershell.exe -WindowStyle $windowStyle -PassThru -ArgumentList "-executionpolicy bypass -File $env:TEMP\Win11Debloat\Win11Debloat.ps1 $arguments" -Verb RunAs
|
||||
$debloatScriptPath = Join-Path $tempWorkPath 'Win11Debloat.ps1'
|
||||
$debloatProcess = Start-Process powershell.exe -WindowStyle $windowStyle -PassThru -ArgumentList "-executionpolicy bypass -File `"$debloatScriptPath`" $arguments" -Verb RunAs
|
||||
|
||||
# Wait for the process to finish before continuing
|
||||
if ($null -ne $debloatProcess) {
|
||||
$debloatProcess.WaitForExit()
|
||||
}
|
||||
|
||||
# Remove all remaining script files, except for CustomAppsList and LastUsedSettings.json files
|
||||
if (Test-Path "$env:TEMP/Win11Debloat") {
|
||||
# Remove all remaining script files, except for configs, logs and backups
|
||||
if (Test-Path $tempWorkPath) {
|
||||
Write-Output ""
|
||||
Write-Output "> Cleaning up..."
|
||||
|
||||
# Cleanup, remove Win11Debloat directory
|
||||
Get-ChildItem -Path "$env:TEMP/Win11Debloat" -Exclude CustomAppsList,LastUsedSettings.json,Win11Debloat.log,Win11Debloat-Run.log,Config,Logs | Remove-Item -Recurse -Force
|
||||
Get-ChildItem -Path $tempWorkPath -Exclude Config,Logs,Backups | Remove-Item -Recurse -Force
|
||||
}
|
||||
|
||||
Write-Output ""
|
||||
|
||||
223
Scripts/Helpers/ApplyRegistryRegFile.ps1
Normal file
223
Scripts/Helpers/ApplyRegistryRegFile.ps1
Normal file
@@ -0,0 +1,223 @@
|
||||
function Get-NormalizedRegistryValueName {
|
||||
param(
|
||||
[AllowNull()]
|
||||
$ValueName
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrEmpty([string]$ValueName)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return [string]$ValueName
|
||||
}
|
||||
|
||||
function Convert-RegOperationToValueKind {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Operation
|
||||
)
|
||||
|
||||
$valueName = if ([string]::IsNullOrEmpty([string]$Operation.ValueName)) { '' } else { [string]$Operation.ValueName }
|
||||
$valueType = [string]$Operation.ValueType
|
||||
$operationKeyPath = [string]$Operation.KeyPath
|
||||
|
||||
switch ($valueType) {
|
||||
'DWord' {
|
||||
$unsigned = [uint32]$Operation.ValueData
|
||||
$value = [BitConverter]::ToInt32([BitConverter]::GetBytes($unsigned), 0)
|
||||
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::DWord; Value = $value }
|
||||
}
|
||||
'String' {
|
||||
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::String; Value = [string]$Operation.ValueData }
|
||||
}
|
||||
'Binary' {
|
||||
return @{ Name = $valueName; Kind = [Microsoft.Win32.RegistryValueKind]::Binary; Value = [byte[]]$Operation.ValueData }
|
||||
}
|
||||
default {
|
||||
throw "Unsupported value type '$valueType' while applying reg operation for '$operationKeyPath'"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Remove-RegistrySubKeyTreeIfExists {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Microsoft.Win32.RegistryKey]$RootKey,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$SubKeyPath
|
||||
)
|
||||
|
||||
try {
|
||||
$RootKey.DeleteSubKeyTree($SubKeyPath, $false)
|
||||
}
|
||||
catch [System.UnauthorizedAccessException], [System.Security.SecurityException] {
|
||||
throw
|
||||
}
|
||||
catch {
|
||||
# Best-effort cleanup only; missing keys are fine.
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RegistryKeyForOperation {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RegistryPath,
|
||||
[switch]$CreateIfMissing,
|
||||
[bool]$OpenKey = $true
|
||||
)
|
||||
|
||||
$parts = Split-RegistryPath -path $RegistryPath
|
||||
if (-not $parts) {
|
||||
throw "Unsupported registry path: $RegistryPath"
|
||||
}
|
||||
|
||||
$rootKey = Get-RegistryRootKey -hiveName $parts.Hive
|
||||
if (-not $rootKey) {
|
||||
throw "Unsupported registry hive '$($parts.Hive)' in path '$RegistryPath'"
|
||||
}
|
||||
|
||||
$subKeyPath = $parts.SubKey
|
||||
if ([string]::IsNullOrWhiteSpace($subKeyPath)) {
|
||||
return [PSCustomObject]@{ RootKey = $rootKey; SubKeyPath = $null; Key = $rootKey }
|
||||
}
|
||||
|
||||
if (-not $OpenKey) {
|
||||
return [PSCustomObject]@{ RootKey = $rootKey; SubKeyPath = $subKeyPath; Key = $null }
|
||||
}
|
||||
|
||||
$key = if ($CreateIfMissing) {
|
||||
$rootKey.CreateSubKey($subKeyPath)
|
||||
}
|
||||
else {
|
||||
$rootKey.OpenSubKey($subKeyPath, $true)
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{ RootKey = $rootKey; SubKeyPath = $subKeyPath; Key = $key }
|
||||
}
|
||||
|
||||
function Invoke-RegistryDeleteValueOperation {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Operation,
|
||||
[Parameter(Mandatory)]
|
||||
$KeyInfo
|
||||
)
|
||||
|
||||
if ($null -eq $KeyInfo.Key) {
|
||||
$valueName = Get-NormalizedRegistryValueName -ValueName $Operation.ValueName
|
||||
$displayValueName = if ([string]::IsNullOrEmpty($valueName)) { '(Default)' } else { $valueName }
|
||||
Write-Verbose "Unable to find or open key '$($Operation.KeyPath)' and value '$displayValueName'"
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
$valueName = Get-NormalizedRegistryValueName -ValueName $Operation.ValueName
|
||||
$KeyInfo.Key.DeleteValue($valueName, $false)
|
||||
}
|
||||
finally {
|
||||
$KeyInfo.Key.Close()
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-RegistrySetValueOperation {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Operation,
|
||||
[Parameter(Mandatory)]
|
||||
$KeyInfo
|
||||
)
|
||||
|
||||
if ($null -eq $KeyInfo.Key) {
|
||||
throw [System.UnauthorizedAccessException]::new("Unable to open or create registry key '$($Operation.KeyPath)'")
|
||||
}
|
||||
|
||||
try {
|
||||
$setArgs = Convert-RegOperationToValueKind -Operation $Operation
|
||||
$KeyInfo.Key.SetValue($setArgs.Name, $setArgs.Value, $setArgs.Kind)
|
||||
}
|
||||
finally {
|
||||
$KeyInfo.Key.Close()
|
||||
}
|
||||
}
|
||||
|
||||
function Write-RegistryOperationAccessDeniedWarning {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Operation,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$ExceptionMessage
|
||||
)
|
||||
|
||||
$keyPath = [string]$Operation.KeyPath
|
||||
$operationType = [string]$Operation.OperationType
|
||||
|
||||
if ($operationType -eq 'SetValue' -or $operationType -eq 'DeleteValue') {
|
||||
$valueName = Get-NormalizedRegistryValueName -ValueName $Operation.ValueName
|
||||
$displayValueName = if ([string]::IsNullOrEmpty($valueName)) { '(Default)' } else { $valueName }
|
||||
Write-Warning "Skipping operation '$operationType' on key '$keyPath' value '$displayValueName' due to access restrictions: $ExceptionMessage"
|
||||
return
|
||||
}
|
||||
|
||||
Write-Warning "Skipping operation '$operationType' on key '$keyPath' due to access restrictions: $ExceptionMessage"
|
||||
}
|
||||
|
||||
function Invoke-RegistryOperation {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$Operation,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RegFilePath
|
||||
)
|
||||
|
||||
$operationType = [string]$Operation.OperationType
|
||||
$isSetValueOperation = $operationType -eq 'SetValue'
|
||||
$isDeleteKeyOperation = $operationType -eq 'DeleteKey'
|
||||
|
||||
$keyInfo = Get-RegistryKeyForOperation -RegistryPath $Operation.KeyPath -CreateIfMissing:$isSetValueOperation -OpenKey:(-not $isDeleteKeyOperation)
|
||||
|
||||
switch ($operationType) {
|
||||
'DeleteKey' {
|
||||
if ($null -ne $keyInfo.SubKeyPath) {
|
||||
Remove-RegistrySubKeyTreeIfExists -RootKey $keyInfo.RootKey -SubKeyPath $keyInfo.SubKeyPath
|
||||
}
|
||||
}
|
||||
'DeleteValue' {
|
||||
Invoke-RegistryDeleteValueOperation -Operation $Operation -KeyInfo $keyInfo
|
||||
}
|
||||
'SetValue' {
|
||||
Invoke-RegistrySetValueOperation -Operation $Operation -KeyInfo $keyInfo
|
||||
}
|
||||
default {
|
||||
throw "Unsupported reg operation type '$($Operation.OperationType)' in '$RegFilePath'"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-RegistryOperationsFromRegFile {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RegFilePath
|
||||
)
|
||||
|
||||
$accessDeniedCount = 0
|
||||
$operations = @(Get-RegFileOperations -regFilePath $RegFilePath)
|
||||
$totalOperations = $operations.Count
|
||||
|
||||
foreach ($operation in $operations) {
|
||||
try {
|
||||
Invoke-RegistryOperation -Operation $operation -RegFilePath $RegFilePath
|
||||
}
|
||||
catch [System.UnauthorizedAccessException], [System.Security.SecurityException] {
|
||||
$accessDeniedCount++
|
||||
Write-RegistryOperationAccessDeniedWarning -Operation $operation -ExceptionMessage $_.Exception.Message
|
||||
}
|
||||
}
|
||||
|
||||
if ($totalOperations -gt 0 -and $accessDeniedCount -eq $totalOperations) {
|
||||
throw "Registry fallback import could not apply any operations in '$RegFilePath' because all $accessDeniedCount operation(s) were blocked by access restrictions."
|
||||
}
|
||||
|
||||
if ($accessDeniedCount -gt 0) {
|
||||
Write-Warning "Registry fallback import completed with $accessDeniedCount access-restricted operation(s) skipped in '$RegFilePath'."
|
||||
}
|
||||
}
|
||||
@@ -1,31 +1,41 @@
|
||||
function CheckIfUserExists {
|
||||
param (
|
||||
$userName
|
||||
[string]$userName
|
||||
)
|
||||
|
||||
if ($userName -match '[<>:"|?*]') {
|
||||
return $false
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($userName)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
$lookupName = $userName.Trim()
|
||||
|
||||
# Validate special characters against the local username segment (user in DOMAIN\user or user@domain).
|
||||
$localUserName = GetLocalUserNameSegment -UserName $lookupName
|
||||
|
||||
if ($localUserName.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -ge 0) {
|
||||
return $false
|
||||
}
|
||||
|
||||
# PowerShell treats [] as wildcard chars in non-literal paths; disallow them explicitly.
|
||||
if ($localUserName -match '[\[\]]') {
|
||||
return $false
|
||||
}
|
||||
|
||||
try {
|
||||
$userExists = Test-Path "$env:SystemDrive\Users\$userName"
|
||||
$userContext = ResolveUserProfileContext -UserName $lookupName
|
||||
if (-not $userContext -or [string]::IsNullOrWhiteSpace($userContext.ProfilePath)) {
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($userExists) {
|
||||
if ($lookupName -ieq 'Default') {
|
||||
return $true
|
||||
}
|
||||
|
||||
$userExists = Test-Path ($env:USERPROFILE -Replace ('\\' + $env:USERNAME + '$'), "\$userName")
|
||||
return -not [string]::IsNullOrWhiteSpace($userContext.UserSid)
|
||||
|
||||
if ($userExists) {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Write-Error "Something went wrong when trying to find the user directory path for user $userName. Please ensure the user exists on this system"
|
||||
Write-Error "Something went wrong when trying to find the user directory path for user $lookupName. Please ensure the user exists on this system"
|
||||
}
|
||||
|
||||
return $false
|
||||
|
||||
34
Scripts/Helpers/ConfirmUnsafeAppRemoval.ps1
Normal file
34
Scripts/Helpers/ConfirmUnsafeAppRemoval.ps1
Normal file
@@ -0,0 +1,34 @@
|
||||
# Shows confirmation dialogs for apps that require extra caution before removal.
|
||||
# Returns $true if the user confirmed all warnings (or if no warnings were triggered),
|
||||
# $false if the user declined any warning.
|
||||
function ConfirmUnsafeAppRemoval {
|
||||
param (
|
||||
[string[]]$SelectedApps,
|
||||
$Owner = $null
|
||||
)
|
||||
|
||||
# Skip all warnings in Silent mode
|
||||
if ($Silent) {
|
||||
return $true
|
||||
}
|
||||
|
||||
# Microsoft Store warning
|
||||
if ($SelectedApps -contains "Microsoft.WindowsStore") {
|
||||
$result = Show-MessageBox -Message 'Are you sure that you wish to uninstall the Microsoft Store? This app cannot easily be reinstalled.' -Title 'Are you sure?' -Button 'YesNo' -Icon 'Warning' -Owner $Owner
|
||||
|
||||
if ($result -eq 'No') {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
# Windows Terminal warning
|
||||
if ($SelectedApps -contains "Microsoft.WindowsTerminal") {
|
||||
$result = Show-MessageBox -Message 'Are you sure that you wish to remove Windows Terminal? Windows Terminal is the default command-line app for Windows. Ensure you are not running Win11Debloat via Windows Terminal before proceeding to avoid a mid-process failure.' -Title 'Are you sure?' -Button 'YesNo' -Icon 'Warning' -Owner $Owner
|
||||
|
||||
if ($result -eq 'No') {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
177
Scripts/Helpers/Get-RegFileOperations.ps1
Normal file
177
Scripts/Helpers/Get-RegFileOperations.ps1
Normal file
@@ -0,0 +1,177 @@
|
||||
function Get-RegFileOperations {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$regFilePath
|
||||
)
|
||||
|
||||
$content = Get-Content -Path $regFilePath -Raw -ErrorAction Stop
|
||||
$rawLines = $content -split "`r?`n"
|
||||
|
||||
# Join continuation lines (lines ending with \)
|
||||
$lines = @()
|
||||
$i = 0
|
||||
while ($i -lt $rawLines.Count) {
|
||||
$line = $rawLines[$i]
|
||||
|
||||
# Join lines that end with backslash to the next line(s)
|
||||
while ($line.EndsWith("\") -and $i + 1 -lt $rawLines.Count) {
|
||||
$line = $line.Substring(0, $line.Length - 1) + $rawLines[$i + 1]
|
||||
$i++
|
||||
}
|
||||
|
||||
$lines += $line
|
||||
$i++
|
||||
}
|
||||
|
||||
$operations = @()
|
||||
$currentKeyPath = $null
|
||||
$isDeletedKey = $false
|
||||
|
||||
foreach ($rawLine in $lines) {
|
||||
$line = $rawLine.Trim()
|
||||
if ([string]::IsNullOrWhiteSpace($line) -or $line.StartsWith(';')) {
|
||||
continue
|
||||
}
|
||||
|
||||
if ($line -match '^Windows Registry Editor Version') {
|
||||
continue
|
||||
}
|
||||
|
||||
if ($line -match '^\[(?<deleted>-)?(?<keyPath>[^\]]+)\]$') {
|
||||
$currentKeyPath = $matches.keyPath.Trim()
|
||||
$isDeletedKey = $matches.deleted -eq '-'
|
||||
|
||||
if ($isDeletedKey) {
|
||||
$operations += [PSCustomObject]@{
|
||||
OperationType = 'DeleteKey'
|
||||
KeyPath = $currentKeyPath
|
||||
}
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $currentKeyPath -or $isDeletedKey) {
|
||||
continue
|
||||
}
|
||||
|
||||
if ($line -notmatch '^(?<valueName>@|"[^"]+")=(?<valueData>.*)$') {
|
||||
continue
|
||||
}
|
||||
|
||||
$valueNameToken = $matches.valueName
|
||||
$valueName = if ($valueNameToken -eq '@') {
|
||||
''
|
||||
}
|
||||
else {
|
||||
$valueNameToken.Trim('"')
|
||||
}
|
||||
|
||||
$parsedValue = Convert-RegValueData -valueData $matches.valueData.Trim()
|
||||
if (-not $parsedValue) { continue }
|
||||
|
||||
$operations += [PSCustomObject]@{
|
||||
OperationType = $parsedValue.OperationType
|
||||
KeyPath = $currentKeyPath
|
||||
ValueName = $valueName
|
||||
ValueType = $parsedValue.ValueType
|
||||
ValueData = $parsedValue.ValueData
|
||||
}
|
||||
}
|
||||
|
||||
return $operations
|
||||
}
|
||||
|
||||
function Convert-RegValueData {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$valueData
|
||||
)
|
||||
|
||||
if ($valueData -eq '-') {
|
||||
return [PSCustomObject]@{
|
||||
OperationType = 'DeleteValue'
|
||||
ValueType = $null
|
||||
ValueData = $null
|
||||
}
|
||||
}
|
||||
|
||||
if ($valueData -match '^dword:(?<value>[0-9a-fA-F]{1,8})$') {
|
||||
return [PSCustomObject]@{
|
||||
OperationType = 'SetValue'
|
||||
ValueType = 'DWord'
|
||||
ValueData = [uint32]::Parse($matches.value, [System.Globalization.NumberStyles]::HexNumber)
|
||||
}
|
||||
}
|
||||
|
||||
if ($valueData -match '^qword:(?<value>[0-9a-fA-F]{1,16})$') {
|
||||
return [PSCustomObject]@{
|
||||
OperationType = 'SetValue'
|
||||
ValueType = 'QWord'
|
||||
ValueData = [uint64]::Parse($matches.value, [System.Globalization.NumberStyles]::HexNumber)
|
||||
}
|
||||
}
|
||||
|
||||
if ($valueData -match '^hex(?:\((?<kind>[0-9a-fA-F]+)\))?:(?<bytes>[0-9a-fA-F,\s]+)$') {
|
||||
$bytes = Convert-HexStringToByteArray -hexValue $matches.bytes
|
||||
$valueType = if ($matches.kind) { "Hex$($matches.kind)" } else { 'Binary' }
|
||||
$value = switch ($matches.kind) {
|
||||
'2' { Convert-RegistryByteArrayToString -byteData $bytes }
|
||||
'7' { Convert-RegistryByteArrayToMultiString -byteData $bytes }
|
||||
default { $bytes }
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
OperationType = 'SetValue'
|
||||
ValueType = $valueType
|
||||
ValueData = $value
|
||||
}
|
||||
}
|
||||
|
||||
if ($valueData -match '^"(?<value>.*)"$') {
|
||||
$stringValue = $matches.value
|
||||
# Unescape registry string escape sequences
|
||||
$stringValue = $stringValue -replace '\\"', '"' -replace '\\\\', '\'
|
||||
return [PSCustomObject]@{
|
||||
OperationType = 'SetValue'
|
||||
ValueType = 'String'
|
||||
ValueData = $stringValue
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function Convert-HexStringToByteArray {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$hexValue
|
||||
)
|
||||
|
||||
$parts = $hexValue.Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }
|
||||
$bytes = New-Object byte[] $parts.Count
|
||||
|
||||
for ($i = 0; $i -lt $parts.Count; $i++) {
|
||||
$bytes[$i] = [byte]::Parse($parts[$i], [System.Globalization.NumberStyles]::HexNumber)
|
||||
}
|
||||
|
||||
return $bytes
|
||||
}
|
||||
|
||||
function Convert-RegistryByteArrayToString {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[byte[]]$byteData
|
||||
)
|
||||
|
||||
return ([System.Text.Encoding]::Unicode.GetString($byteData)).TrimEnd([char]0)
|
||||
}
|
||||
|
||||
function Convert-RegistryByteArrayToMultiString {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[byte[]]$byteData
|
||||
)
|
||||
|
||||
return @(([System.Text.Encoding]::Unicode.GetString($byteData)).TrimEnd([char]0) -split "`0" | Where-Object { $_ -ne '' })
|
||||
}
|
||||
43
Scripts/Helpers/GetFriendlyRegistryBackupTarget.ps1
Normal file
43
Scripts/Helpers/GetFriendlyRegistryBackupTarget.ps1
Normal file
@@ -0,0 +1,43 @@
|
||||
function GetFriendlyRegistryBackupTarget {
|
||||
param(
|
||||
[AllowNull()]
|
||||
[AllowEmptyString()]
|
||||
[string]$Target
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Target)) {
|
||||
return 'Unknown'
|
||||
}
|
||||
|
||||
if ($Target -eq 'DefaultUserProfile') {
|
||||
return 'Default user profile'
|
||||
}
|
||||
|
||||
if ($Target -eq 'CurrentUser') {
|
||||
return 'Current user'
|
||||
}
|
||||
|
||||
if ($Target -eq 'AllUsers') {
|
||||
return 'All users'
|
||||
}
|
||||
|
||||
if ($Target -like 'CurrentUser:*') {
|
||||
$userName = $Target.Substring(12)
|
||||
if ([string]::IsNullOrWhiteSpace($userName)) {
|
||||
return 'Current user'
|
||||
}
|
||||
|
||||
return "Current user ($userName)"
|
||||
}
|
||||
|
||||
if ($Target -like 'User:*') {
|
||||
$userName = $Target.Substring(5)
|
||||
if ([string]::IsNullOrWhiteSpace($userName)) {
|
||||
return 'User'
|
||||
}
|
||||
|
||||
return "User ($userName)"
|
||||
}
|
||||
|
||||
return $Target
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
# Returns the feature metadata for a parameter when it supports undo; otherwise returns $null.
|
||||
function GetUndoFeatureForParam {
|
||||
param (
|
||||
[string]$paramKey
|
||||
)
|
||||
|
||||
if (-not $script:Features -or -not $script:Features.ContainsKey($paramKey)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$feature = $script:Features[$paramKey]
|
||||
if (-not ($feature.RegistryUndoKey -and ($feature.UndoText -or $feature.UndoAction))) {
|
||||
return $null
|
||||
}
|
||||
|
||||
return $feature
|
||||
}
|
||||
@@ -7,23 +7,41 @@ function GetUserDirectory {
|
||||
)
|
||||
|
||||
try {
|
||||
if (-not (CheckIfUserExists -userName $userName) -and $userName -ne "*") {
|
||||
Write-Error "User $userName does not exist on this system"
|
||||
AwaitKeyToExit
|
||||
if ($userName -eq "*") {
|
||||
$rootPaths = @(
|
||||
(Join-Path $env:SystemDrive 'Users')
|
||||
(Split-Path -Path $env:USERPROFILE -Parent)
|
||||
) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
|
||||
|
||||
foreach ($rootPath in $rootPaths) {
|
||||
if (-not (Test-Path -LiteralPath $rootPath -PathType Container)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$wildcardPath = if ([string]::IsNullOrWhiteSpace($fileName)) {
|
||||
Join-Path $rootPath '*'
|
||||
}
|
||||
else {
|
||||
Join-Path (Join-Path $rootPath '*') $fileName
|
||||
}
|
||||
|
||||
return $wildcardPath
|
||||
}
|
||||
}
|
||||
|
||||
$userDirectoryExists = Test-Path "$env:SystemDrive\Users\$userName"
|
||||
$userPath = "$env:SystemDrive\Users\$userName\$fileName"
|
||||
$userContext = ResolveUserProfileContext -UserName $userName
|
||||
$resolvedUserDirectory = if ($userContext) { $userContext.ProfilePath } else { $null }
|
||||
if ($resolvedUserDirectory) {
|
||||
$userPath = if ([string]::IsNullOrWhiteSpace($fileName)) {
|
||||
$resolvedUserDirectory
|
||||
}
|
||||
else {
|
||||
Join-Path $resolvedUserDirectory $fileName
|
||||
}
|
||||
|
||||
if ((Test-Path $userPath) -or ($userDirectoryExists -and (-not $exitIfPathNotFound))) {
|
||||
return $userPath
|
||||
}
|
||||
|
||||
$userDirectoryExists = Test-Path ($env:USERPROFILE -Replace ('\\' + $env:USERNAME + '$'), "\$userName")
|
||||
$userPath = $env:USERPROFILE -Replace ('\\' + $env:USERNAME + '$'), "\$userName\$fileName"
|
||||
|
||||
if ((Test-Path $userPath) -or ($userDirectoryExists -and (-not $exitIfPathNotFound))) {
|
||||
return $userPath
|
||||
if ((Test-Path -LiteralPath $userPath) -or ((Test-Path -LiteralPath $resolvedUserDirectory -PathType Container) -and (-not $exitIfPathNotFound))) {
|
||||
return $userPath
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
|
||||
83
Scripts/Helpers/RegistryPathHelpers.ps1
Normal file
83
Scripts/Helpers/RegistryPathHelpers.ps1
Normal file
@@ -0,0 +1,83 @@
|
||||
function Split-RegistryPath {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$path
|
||||
)
|
||||
|
||||
$normalizedPath = [string]$path
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedPath)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$normalizedPath = $normalizedPath.Trim().Replace('/', '\')
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedPath)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if ($normalizedPath -notmatch '^(?<hive>HKEY_[^\\]+)(?:\\(?<subKey>.*))?$') {
|
||||
return $null
|
||||
}
|
||||
|
||||
$hiveName = [string]$matches.hive
|
||||
|
||||
$normalizedSubKey = if ($null -ne $matches.subKey) {
|
||||
([string]$matches.subKey).Trim('\\')
|
||||
}
|
||||
else {
|
||||
$null
|
||||
}
|
||||
|
||||
if ($hiveName.Equals('HKEY_USERS', [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
-not [string]::IsNullOrWhiteSpace($normalizedSubKey) -and
|
||||
-not [string]::IsNullOrWhiteSpace([string]$script:RegistryTargetHiveMountName)) {
|
||||
if ($normalizedSubKey -match '^(?<mount>[^\\]+)(?:\\(?<rest>.*))?$') {
|
||||
$mountName = [string]$matches.mount
|
||||
if ($mountName.Equals('Default', [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
$remainingSubKey = if ($matches.rest) { [string]$matches.rest } else { '' }
|
||||
$targetMountName = [string]$script:RegistryTargetHiveMountName
|
||||
if ([string]::IsNullOrWhiteSpace($remainingSubKey)) {
|
||||
$normalizedSubKey = $targetMountName
|
||||
}
|
||||
else {
|
||||
$normalizedSubKey = "$targetMountName\$remainingSubKey"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
Hive = $hiveName
|
||||
SubKey = $normalizedSubKey
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RegistryRootKey {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$hiveName
|
||||
)
|
||||
|
||||
switch ($hiveName.ToUpperInvariant()) {
|
||||
'HKEY_CURRENT_USER' { return [Microsoft.Win32.Registry]::CurrentUser }
|
||||
'HKEY_LOCAL_MACHINE' { return [Microsoft.Win32.Registry]::LocalMachine }
|
||||
'HKEY_CLASSES_ROOT' { return [Microsoft.Win32.Registry]::ClassesRoot }
|
||||
'HKEY_USERS' { return [Microsoft.Win32.Registry]::Users }
|
||||
'HKEY_CURRENT_CONFIG' { return [Microsoft.Win32.Registry]::CurrentConfig }
|
||||
default { return $null }
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RegistryFilePathForFeature {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$RegistryKey,
|
||||
[switch]$UseSysprepRegFiles
|
||||
)
|
||||
|
||||
$useSysprepLayout = $UseSysprepRegFiles -or $script:Params.ContainsKey('Sysprep') -or $script:Params.ContainsKey('User')
|
||||
if ($useSysprepLayout) {
|
||||
return Join-Path (Join-Path $script:RegfilesPath 'Sysprep') $RegistryKey
|
||||
}
|
||||
|
||||
return Join-Path $script:RegfilesPath $RegistryKey
|
||||
}
|
||||
382
Scripts/Helpers/ResolveUserProfilePath.ps1
Normal file
382
Scripts/Helpers/ResolveUserProfilePath.ps1
Normal file
@@ -0,0 +1,382 @@
|
||||
function NormalizeUserLookupValue {
|
||||
param(
|
||||
[string]$Value
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Value)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
# Remove zero-width characters and normalize whitespace for robust comparisons.
|
||||
$normalized = $Value -replace '[\u200B-\u200D\uFEFF]', ''
|
||||
$normalized = $normalized.Trim() -replace '\s+', ' '
|
||||
return $normalized
|
||||
}
|
||||
|
||||
if (-not $script:ResolvedUserSidCache) {
|
||||
$script:ResolvedUserSidCache = @{}
|
||||
}
|
||||
|
||||
function GetUserLookupCacheKey {
|
||||
param(
|
||||
[string]$Value
|
||||
)
|
||||
|
||||
$normalizedValue = NormalizeUserLookupValue -Value $Value
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedValue)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return $normalizedValue.ToLowerInvariant()
|
||||
}
|
||||
|
||||
function EscapeWqlString {
|
||||
param(
|
||||
[string]$Value
|
||||
)
|
||||
|
||||
if ($null -eq $Value) {
|
||||
return ''
|
||||
}
|
||||
|
||||
return $Value -replace "'", "''"
|
||||
}
|
||||
|
||||
function GetLocalUserNameSegment {
|
||||
param(
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
$normalizedName = NormalizeUserLookupValue -Value $UserName
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedName)) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if ($normalizedName.Contains('\')) {
|
||||
return NormalizeUserLookupValue -Value (($normalizedName -split '\\')[-1])
|
||||
}
|
||||
|
||||
if ($normalizedName.Contains('@')) {
|
||||
return NormalizeUserLookupValue -Value (($normalizedName -split '@')[0])
|
||||
}
|
||||
|
||||
return $normalizedName
|
||||
}
|
||||
|
||||
function SetResolvedUserSidCache {
|
||||
param(
|
||||
[string[]]$Candidates,
|
||||
[string]$Sid
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($Sid)) {
|
||||
return
|
||||
}
|
||||
|
||||
foreach ($candidate in @($Candidates)) {
|
||||
$cacheKey = GetUserLookupCacheKey -Value $candidate
|
||||
if ($cacheKey) {
|
||||
$script:ResolvedUserSidCache[$cacheKey] = $Sid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function GetCachedResolvedUserSid {
|
||||
param(
|
||||
[string[]]$Candidates
|
||||
)
|
||||
|
||||
foreach ($candidate in @($Candidates)) {
|
||||
$cacheKey = GetUserLookupCacheKey -Value $candidate
|
||||
if ($cacheKey -and $script:ResolvedUserSidCache.ContainsKey($cacheKey)) {
|
||||
return $script:ResolvedUserSidCache[$cacheKey]
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function TryResolveSidByNtAccount {
|
||||
param(
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($UserName)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
try {
|
||||
$ntAccount = [System.Security.Principal.NTAccount]::new($UserName)
|
||||
$sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier])
|
||||
if ($sid) {
|
||||
return $sid.Value
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Fallback handled by caller.
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function TryResolveSidByLocalLookup {
|
||||
param(
|
||||
[string[]]$Candidates
|
||||
)
|
||||
|
||||
$lookupCandidates = @($Candidates) | ForEach-Object { NormalizeUserLookupValue -Value $_ } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
|
||||
if ($lookupCandidates.Count -eq 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
if (Get-Command -Name Get-LocalUser -ErrorAction SilentlyContinue) {
|
||||
foreach ($candidate in $lookupCandidates) {
|
||||
try {
|
||||
$matchingLocalUser = Get-LocalUser -Name $candidate -ErrorAction Stop | Select-Object -First 1
|
||||
if ($matchingLocalUser -and $matchingLocalUser.SID) {
|
||||
return $matchingLocalUser.SID.Value
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Continue to next lookup strategy.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($candidate in $lookupCandidates) {
|
||||
try {
|
||||
$escapedCandidate = EscapeWqlString -Value $candidate
|
||||
$escapedComputerName = EscapeWqlString -Value $env:COMPUTERNAME
|
||||
$filter = "LocalAccount=True AND (Name='$escapedCandidate' OR FullName='$escapedCandidate' OR Caption='$escapedComputerName\$escapedCandidate')"
|
||||
$matchingAccount = Get-CimInstance -ClassName Win32_UserAccount -Filter $filter -ErrorAction Stop | Select-Object -First 1
|
||||
|
||||
if ($matchingAccount -and $matchingAccount.SID) {
|
||||
return $matchingAccount.SID
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Continue to next lookup strategy.
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function TryResolveSidFromProfileList {
|
||||
param(
|
||||
[string[]]$Candidates
|
||||
)
|
||||
|
||||
$lookupCandidates = @($Candidates) | ForEach-Object { NormalizeUserLookupValue -Value $_ } | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
|
||||
if ($lookupCandidates.Count -eq 0) {
|
||||
return $null
|
||||
}
|
||||
|
||||
try {
|
||||
$profileListPath = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
|
||||
foreach ($sidKey in @(Get-ChildItem -LiteralPath $profileListPath -ErrorAction Stop)) {
|
||||
try {
|
||||
$imagePath = Get-ItemPropertyValue -LiteralPath $sidKey.PSPath -Name 'ProfileImagePath' -ErrorAction Stop
|
||||
if ([string]::IsNullOrWhiteSpace($imagePath)) { continue }
|
||||
|
||||
$expandedPath = [System.Environment]::ExpandEnvironmentVariables($imagePath)
|
||||
$leafName = NormalizeUserLookupValue -Value (Split-Path -Leaf $expandedPath)
|
||||
|
||||
foreach ($candidate in $lookupCandidates) {
|
||||
if ($leafName -ieq $candidate) {
|
||||
return $sidKey.PSChildName
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Fallback handled by caller.
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function NewResolvedUserContext {
|
||||
param(
|
||||
[string]$UserName,
|
||||
[string]$UserSid,
|
||||
[string]$ProfilePath
|
||||
)
|
||||
|
||||
return [PSCustomObject]@{
|
||||
UserName = $UserName
|
||||
UserSid = $UserSid
|
||||
ProfilePath = $ProfilePath
|
||||
}
|
||||
}
|
||||
|
||||
function ResolveUserSid {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
$candidateUserName = NormalizeUserLookupValue -Value $UserName
|
||||
if ([string]::IsNullOrWhiteSpace($candidateUserName)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$hasQualifiedIdentity = $candidateUserName.Contains('\') -or $candidateUserName.Contains('@')
|
||||
$localNameSegment = GetLocalUserNameSegment -UserName $candidateUserName
|
||||
$leafNameCandidates = @()
|
||||
if ($hasQualifiedIdentity -and -not [string]::IsNullOrWhiteSpace($localNameSegment) -and $localNameSegment -ine $candidateUserName) {
|
||||
$leafNameCandidates = @($localNameSegment)
|
||||
}
|
||||
|
||||
$cacheCandidates = if ($hasQualifiedIdentity) {
|
||||
@($candidateUserName)
|
||||
}
|
||||
else {
|
||||
@($candidateUserName) + $leafNameCandidates | Select-Object -Unique
|
||||
}
|
||||
|
||||
$localLookupCandidates = if ($hasQualifiedIdentity) {
|
||||
@()
|
||||
}
|
||||
else {
|
||||
@($candidateUserName) + $leafNameCandidates | Select-Object -Unique
|
||||
}
|
||||
|
||||
$profileHeuristicCandidates = if ($leafNameCandidates.Count -gt 0) {
|
||||
$leafNameCandidates
|
||||
}
|
||||
else {
|
||||
@($candidateUserName)
|
||||
}
|
||||
|
||||
$cachedSid = GetCachedResolvedUserSid -Candidates $cacheCandidates
|
||||
if ($cachedSid) {
|
||||
return $cachedSid
|
||||
}
|
||||
|
||||
# Resolve fully-qualified identities first to avoid accidentally matching a local leaf account.
|
||||
if ($hasQualifiedIdentity) {
|
||||
$resolvedSid = TryResolveSidByNtAccount -UserName $candidateUserName
|
||||
if ($resolvedSid) {
|
||||
SetResolvedUserSidCache -Candidates $cacheCandidates -Sid $resolvedSid
|
||||
return $resolvedSid
|
||||
}
|
||||
}
|
||||
|
||||
$resolvedSid = TryResolveSidByLocalLookup -Candidates $localLookupCandidates
|
||||
if ($resolvedSid) {
|
||||
SetResolvedUserSidCache -Candidates $cacheCandidates -Sid $resolvedSid
|
||||
return $resolvedSid
|
||||
}
|
||||
|
||||
# Last-ditch NTAccount translation for non-qualified names.
|
||||
if (-not $hasQualifiedIdentity) {
|
||||
$resolvedSid = TryResolveSidByNtAccount -UserName $candidateUserName
|
||||
if ($resolvedSid) {
|
||||
SetResolvedUserSidCache -Candidates $cacheCandidates -Sid $resolvedSid
|
||||
return $resolvedSid
|
||||
}
|
||||
}
|
||||
|
||||
$resolvedSid = TryResolveSidFromProfileList -Candidates $profileHeuristicCandidates
|
||||
if ($resolvedSid) {
|
||||
SetResolvedUserSidCache -Candidates $cacheCandidates -Sid $resolvedSid
|
||||
return $resolvedSid
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function ResolveUserProfilePath {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
$userContext = ResolveUserProfileContext -UserName $UserName
|
||||
if ($userContext) {
|
||||
return $userContext.ProfilePath
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
function ResolveUserProfileContext {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($UserName)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$candidateUserName = NormalizeUserLookupValue -Value $UserName
|
||||
$rootPaths = @(
|
||||
(Join-Path $env:SystemDrive 'Users')
|
||||
(Split-Path -Path $env:USERPROFILE -Parent)
|
||||
) | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique
|
||||
|
||||
if ($candidateUserName -ieq 'Default') {
|
||||
foreach ($rootPath in $rootPaths) {
|
||||
if (-not (Test-Path -LiteralPath $rootPath -PathType Container)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$defaultProfilePath = Join-Path $rootPath 'Default'
|
||||
if (Test-Path -LiteralPath $defaultProfilePath -PathType Container) {
|
||||
return (NewResolvedUserContext -UserName $candidateUserName -UserSid $null -ProfilePath $defaultProfilePath)
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
$userSid = ResolveUserSid -UserName $candidateUserName
|
||||
|
||||
if ($userSid) {
|
||||
$sidRegistryPath = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$userSid"
|
||||
try {
|
||||
if (Test-Path -LiteralPath $sidRegistryPath) {
|
||||
$registryImagePath = Get-ItemPropertyValue -LiteralPath $sidRegistryPath -Name 'ProfileImagePath' -ErrorAction Stop
|
||||
if (-not [string]::IsNullOrWhiteSpace($registryImagePath)) {
|
||||
$expandedPath = [System.Environment]::ExpandEnvironmentVariables($registryImagePath)
|
||||
if (Test-Path -LiteralPath $expandedPath -PathType Container) {
|
||||
return (NewResolvedUserContext -UserName $candidateUserName -UserSid $userSid -ProfilePath $expandedPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Try Win32_UserProfile fallback.
|
||||
}
|
||||
|
||||
try {
|
||||
$matchingProfiles = @(Get-CimInstance -ClassName Win32_UserProfile -Filter "SID='$userSid'" -ErrorAction Stop)
|
||||
$resolvedProfile = $matchingProfiles | Where-Object { -not [string]::IsNullOrWhiteSpace($_.LocalPath) } | Select-Object -First 1
|
||||
if ($resolvedProfile -and (Test-Path -LiteralPath $resolvedProfile.LocalPath -PathType Container)) {
|
||||
return (NewResolvedUserContext -UserName $candidateUserName -UserSid $userSid -ProfilePath $resolvedProfile.LocalPath)
|
||||
}
|
||||
}
|
||||
catch {
|
||||
# Fall through to legacy path probing.
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($rootPath in $rootPaths) {
|
||||
if (-not (Test-Path -LiteralPath $rootPath -PathType Container)) {
|
||||
continue
|
||||
}
|
||||
|
||||
$candidateUserPath = Join-Path $rootPath $candidateUserName
|
||||
if (Test-Path -LiteralPath $candidateUserPath -PathType Container) {
|
||||
return (NewResolvedUserContext -UserName $candidateUserName -UserSid $userSid -ProfilePath $candidateUserPath)
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
39
Scripts/Helpers/Test-TargetUserName.ps1
Normal file
39
Scripts/Helpers/Test-TargetUserName.ps1
Normal file
@@ -0,0 +1,39 @@
|
||||
function Test-TargetUserName {
|
||||
param(
|
||||
[AllowNull()]
|
||||
[AllowEmptyString()]
|
||||
[string]$UserName
|
||||
)
|
||||
|
||||
$normalizedUserName = if ($null -ne $UserName) { $UserName.Trim() } else { '' }
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedUserName)) {
|
||||
return [PSCustomObject]@{
|
||||
IsValid = $false
|
||||
UserName = $normalizedUserName
|
||||
Message = 'Please enter a username'
|
||||
}
|
||||
}
|
||||
|
||||
if ($normalizedUserName -eq $env:USERNAME) {
|
||||
return [PSCustomObject]@{
|
||||
IsValid = $false
|
||||
UserName = $normalizedUserName
|
||||
Message = "Cannot enter your own username, use 'Current User' option instead"
|
||||
}
|
||||
}
|
||||
|
||||
if (-not (CheckIfUserExists -userName $normalizedUserName)) {
|
||||
return [PSCustomObject]@{
|
||||
IsValid = $false
|
||||
UserName = $normalizedUserName
|
||||
Message = 'User not found, please enter a valid username'
|
||||
}
|
||||
}
|
||||
|
||||
return [PSCustomObject]@{
|
||||
IsValid = $true
|
||||
UserName = $normalizedUserName
|
||||
Message = "User found: $normalizedUserName"
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
function TestIfUserIsLoggedIn {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Username
|
||||
)
|
||||
|
||||
try {
|
||||
$quserOutput = @(& quser 2>$null)
|
||||
if ($LASTEXITCODE -ne 0 -or -not $quserOutput) {
|
||||
return $false
|
||||
}
|
||||
|
||||
foreach ($line in ($quserOutput | Select-Object -Skip 1)) {
|
||||
if ([string]::IsNullOrWhiteSpace($line)) { continue }
|
||||
|
||||
# Remove current-session marker and split columns.
|
||||
$normalizedLine = $line.TrimStart('>', ' ')
|
||||
$parts = $normalizedLine -split '\s+'
|
||||
if ($parts.Count -eq 0) { continue }
|
||||
|
||||
$sessionUser = $parts[0]
|
||||
if ([string]::IsNullOrWhiteSpace($sessionUser)) { continue }
|
||||
|
||||
# Normalize possible DOMAIN\user or user@domain formats.
|
||||
if ($sessionUser.Contains('\')) {
|
||||
$sessionUser = ($sessionUser -split '\\')[-1]
|
||||
}
|
||||
if ($sessionUser.Contains('@')) {
|
||||
$sessionUser = ($sessionUser -split '@')[0]
|
||||
}
|
||||
|
||||
if ($sessionUser.Equals($Username, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
return $true
|
||||
}
|
||||
}
|
||||
}
|
||||
catch {
|
||||
return $false
|
||||
}
|
||||
|
||||
return $false
|
||||
}
|
||||
152
Scripts/Helpers/UserHiveHelpers.ps1
Normal file
152
Scripts/Helpers/UserHiveHelpers.ps1
Normal file
@@ -0,0 +1,152 @@
|
||||
function New-TargetUserHiveContext {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$TargetUserName,
|
||||
[AllowNull()]
|
||||
[object]$UserContext,
|
||||
[Parameter(Mandatory)]
|
||||
[string]$HiveDatPath,
|
||||
[AllowNull()]
|
||||
[string]$MountName,
|
||||
[bool]$WasAlreadyLoaded = $false,
|
||||
[bool]$WasLoadedByScript = $false
|
||||
)
|
||||
|
||||
$effectiveMountName = if ([string]::IsNullOrWhiteSpace($MountName)) { 'Default' } else { $MountName }
|
||||
|
||||
return [PSCustomObject]@{
|
||||
TargetUserName = $TargetUserName
|
||||
UserSid = if ($UserContext) { $UserContext.UserSid } else { $null }
|
||||
ProfilePath = if ($UserContext) { $UserContext.ProfilePath } else { $null }
|
||||
HiveDatPath = $HiveDatPath
|
||||
MountName = $effectiveMountName
|
||||
WasAlreadyLoaded = $WasAlreadyLoaded
|
||||
WasLoadedByScript = $WasLoadedByScript
|
||||
}
|
||||
}
|
||||
|
||||
function Resolve-TargetUserHiveContext {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$TargetUserName
|
||||
)
|
||||
|
||||
$normalizedTargetUserName = NormalizeUserLookupValue -Value $TargetUserName
|
||||
if ([string]::IsNullOrWhiteSpace($normalizedTargetUserName)) {
|
||||
throw 'Target user name for registry hive resolution is empty.'
|
||||
}
|
||||
|
||||
$userContext = ResolveUserProfileContext -UserName $normalizedTargetUserName
|
||||
if (-not $userContext -or [string]::IsNullOrWhiteSpace([string]$userContext.ProfilePath)) {
|
||||
throw "Unable to resolve profile path for target user '$normalizedTargetUserName'."
|
||||
}
|
||||
|
||||
$hiveDatPath = Join-Path $userContext.ProfilePath 'NTUSER.DAT'
|
||||
if (-not (Test-Path -LiteralPath $hiveDatPath)) {
|
||||
throw "Unable to find target user hive at '$hiveDatPath'."
|
||||
}
|
||||
|
||||
$isDefaultProfile = $normalizedTargetUserName.Equals('Default', [System.StringComparison]::OrdinalIgnoreCase)
|
||||
$userSid = if ($userContext) { [string]$userContext.UserSid } else { '' }
|
||||
|
||||
if ((-not $isDefaultProfile) -and (-not [string]::IsNullOrWhiteSpace($userSid))) {
|
||||
$loadedHivePath = "Registry::HKEY_USERS\$userSid"
|
||||
if (Test-Path -LiteralPath $loadedHivePath) {
|
||||
return (New-TargetUserHiveContext `
|
||||
-TargetUserName $normalizedTargetUserName `
|
||||
-UserContext $userContext `
|
||||
-HiveDatPath $hiveDatPath `
|
||||
-MountName $userSid `
|
||||
-WasAlreadyLoaded $true `
|
||||
-WasLoadedByScript $false)
|
||||
}
|
||||
}
|
||||
|
||||
return (New-TargetUserHiveContext `
|
||||
-TargetUserName $normalizedTargetUserName `
|
||||
-UserContext $userContext `
|
||||
-HiveDatPath $hiveDatPath `
|
||||
-MountName 'Default' `
|
||||
-WasAlreadyLoaded $false `
|
||||
-WasLoadedByScript $false)
|
||||
}
|
||||
|
||||
function Resolve-LoadedTargetUserHiveContext {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
$HiveContext
|
||||
)
|
||||
|
||||
$userSid = [string]$HiveContext.UserSid
|
||||
if ([string]::IsNullOrWhiteSpace($userSid)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
$loadedHivePath = "Registry::HKEY_USERS\$userSid"
|
||||
if (-not (Test-Path -LiteralPath $loadedHivePath)) {
|
||||
return $null
|
||||
}
|
||||
|
||||
return (New-TargetUserHiveContext `
|
||||
-TargetUserName $HiveContext.TargetUserName `
|
||||
-UserContext ([PSCustomObject]@{ UserSid = $HiveContext.UserSid; ProfilePath = $HiveContext.ProfilePath }) `
|
||||
-HiveDatPath $HiveContext.HiveDatPath `
|
||||
-MountName $userSid `
|
||||
-WasAlreadyLoaded $true `
|
||||
-WasLoadedByScript $false)
|
||||
}
|
||||
|
||||
function Invoke-WithTargetUserHive {
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$TargetUserName,
|
||||
[Parameter(Mandatory)]
|
||||
[scriptblock]$ScriptBlock,
|
||||
$ArgumentObject = $null,
|
||||
[switch]$PassHiveContext
|
||||
)
|
||||
|
||||
$hiveContext = Resolve-TargetUserHiveContext -TargetUserName $TargetUserName
|
||||
$previousHiveMountName = $script:RegistryTargetHiveMountName
|
||||
|
||||
try {
|
||||
if (-not $hiveContext.WasAlreadyLoaded) {
|
||||
$global:LASTEXITCODE = 0
|
||||
reg load "HKU\$($hiveContext.MountName)" "$($hiveContext.HiveDatPath)" | Out-Null
|
||||
$loadExitCode = $LASTEXITCODE
|
||||
|
||||
if ($loadExitCode -ne 0) {
|
||||
$loadedSidContext = Resolve-LoadedTargetUserHiveContext -HiveContext $hiveContext
|
||||
if ($loadedSidContext) {
|
||||
$hiveContext = $loadedSidContext
|
||||
}
|
||||
else {
|
||||
throw "Failed to load target user hive '$($hiveContext.HiveDatPath)' (exit code: $loadExitCode)."
|
||||
}
|
||||
}
|
||||
else {
|
||||
$hiveContext.WasLoadedByScript = $true
|
||||
}
|
||||
}
|
||||
|
||||
$script:RegistryTargetHiveMountName = [string]$hiveContext.MountName
|
||||
|
||||
if ($PassHiveContext) {
|
||||
return & $ScriptBlock $ArgumentObject $hiveContext
|
||||
}
|
||||
|
||||
return & $ScriptBlock $ArgumentObject
|
||||
}
|
||||
finally {
|
||||
$script:RegistryTargetHiveMountName = $previousHiveMountName
|
||||
|
||||
if ($hiveContext -and $hiveContext.WasLoadedByScript) {
|
||||
$global:LASTEXITCODE = 0
|
||||
reg unload "HKU\$($hiveContext.MountName)" | Out-Null
|
||||
$unloadExitCode = $LASTEXITCODE
|
||||
if ($unloadExitCode -ne 0) {
|
||||
Write-Warning "Failed to unload registry hive 'HKU\$($hiveContext.MountName)' (exit code: $unloadExitCode)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
155
Win11Debloat.ps1
155
Win11Debloat.ps1
@@ -2,7 +2,6 @@
|
||||
param (
|
||||
[switch]$CLI,
|
||||
[switch]$Silent,
|
||||
[switch]$Undo,
|
||||
[switch]$Sysprep,
|
||||
[string]$LogPath,
|
||||
[string]$User,
|
||||
@@ -18,9 +17,7 @@ param (
|
||||
[switch]$RemoveApps,
|
||||
[switch]$RemoveAppsCustom,
|
||||
[switch]$RemoveGamingApps,
|
||||
[switch]$RemoveCommApps,
|
||||
[switch]$RemoveHPApps,
|
||||
[switch]$RemoveW11Outlook,
|
||||
[switch]$ForceRemoveEdge,
|
||||
[switch]$DisableDVR,
|
||||
[switch]$DisableGameBarIntegration,
|
||||
@@ -60,7 +57,7 @@ param (
|
||||
[switch]$HideSearchTb, [switch]$ShowSearchIconTb, [switch]$ShowSearchLabelTb, [switch]$ShowSearchBoxTb,
|
||||
[switch]$HideTaskview,
|
||||
[switch]$DisableStartRecommended,
|
||||
[switch]$DisableStartAllApps,
|
||||
[switch]$DisableStartAllApps, [switch]$StartAllAppsCategory, [switch]$StartAllAppsGrid, [switch]$StartAllAppsList,
|
||||
[switch]$DisableStartPhoneLink,
|
||||
[switch]$DisableCopilot,
|
||||
[switch]$DisableRecall,
|
||||
@@ -142,28 +139,33 @@ if (-not $isAdmin) {
|
||||
}
|
||||
|
||||
# Define script-level variables & paths
|
||||
$script:Version = "2026.04.05"
|
||||
$script:FeaturesConfigVersion = "2.0"
|
||||
$script:AppsListFilePath = "$PSScriptRoot/Config/Apps.json"
|
||||
$script:DefaultSettingsFilePath = "$PSScriptRoot/Config/DefaultSettings.json"
|
||||
$script:FeaturesFilePath = "$PSScriptRoot/Config/Features.json"
|
||||
$script:SavedSettingsFilePath = "$PSScriptRoot/Config/LastUsedSettings.json"
|
||||
$script:CustomAppsListFilePath = "$PSScriptRoot/Config/CustomAppsList"
|
||||
$script:DefaultLogPath = "$PSScriptRoot/Logs/Win11Debloat.log"
|
||||
$script:RegfilesPath = "$PSScriptRoot/Regfiles"
|
||||
$script:AssetsPath = "$PSScriptRoot/Assets"
|
||||
$script:AppSelectionSchema = "$PSScriptRoot/Schemas/AppSelectionWindow.xaml"
|
||||
$script:MainWindowSchema = "$PSScriptRoot/Schemas/MainWindow.xaml"
|
||||
$script:MessageBoxSchema = "$PSScriptRoot/Schemas/MessageBoxWindow.xaml"
|
||||
$script:AboutWindowSchema = "$PSScriptRoot/Schemas/AboutWindow.xaml"
|
||||
$script:ApplyChangesWindowSchema = "$PSScriptRoot/Schemas/ApplyChangesWindow.xaml"
|
||||
$script:RevertSettingsWindowSchema = "$PSScriptRoot/Schemas/RevertSettingsWindow.xaml"
|
||||
$script:SharedStylesSchema = "$PSScriptRoot/Schemas/SharedStyles.xaml"
|
||||
$script:BubbleHintSchema = "$PSScriptRoot/Schemas/BubbleHint.xaml"
|
||||
$script:ImportExportConfigSchema = "$PSScriptRoot/Schemas/ImportExportConfigWindow.xaml"
|
||||
$script:LoadAppsDetailsScriptPath = "$PSScriptRoot/Scripts/FileIO/LoadAppsDetailsFromJson.ps1"
|
||||
$script:Version = "2026.05.20"
|
||||
$configPath = Join-Path $PSScriptRoot 'Config'
|
||||
$logsPath = Join-Path $PSScriptRoot 'Logs'
|
||||
$schemasPath = Join-Path $PSScriptRoot 'Schemas'
|
||||
$scriptsPath = Join-Path $PSScriptRoot 'Scripts'
|
||||
|
||||
$script:ControlParams = 'WhatIf', 'Confirm', 'Verbose', 'Debug', 'LogPath', 'Silent', 'Undo', 'Sysprep', 'User', 'NoRestartExplorer', 'RunDefaults', 'RunDefaultsLite', 'RunSavedSettings', 'Config', 'RunAppsListGenerator', 'CLI', 'AppRemovalTarget'
|
||||
$script:AppsListFilePath = Join-Path $configPath 'Apps.json'
|
||||
$script:DefaultSettingsFilePath = Join-Path $configPath 'DefaultSettings.json'
|
||||
$script:FeaturesFilePath = Join-Path $configPath 'Features.json'
|
||||
$script:SavedSettingsFilePath = Join-Path $configPath 'LastUsedSettings.json'
|
||||
$script:CustomAppsListFilePath = Join-Path $configPath 'CustomAppsList'
|
||||
$script:DefaultLogPath = Join-Path $logsPath 'Win11Debloat.log'
|
||||
$script:RegfilesPath = Join-Path $PSScriptRoot 'Regfiles'
|
||||
$script:RegistryBackupsPath = Join-Path $PSScriptRoot 'Backups'
|
||||
$script:AssetsPath = Join-Path $PSScriptRoot 'Assets'
|
||||
$script:AppSelectionSchema = Join-Path $schemasPath 'AppSelectionWindow.xaml'
|
||||
$script:MainWindowSchema = Join-Path $schemasPath 'MainWindow.xaml'
|
||||
$script:MessageBoxSchema = Join-Path $schemasPath 'MessageBoxWindow.xaml'
|
||||
$script:AboutWindowSchema = Join-Path $schemasPath 'AboutWindow.xaml'
|
||||
$script:ApplyChangesWindowSchema = Join-Path $schemasPath 'ApplyChangesWindow.xaml'
|
||||
$script:SharedStylesSchema = Join-Path $schemasPath 'SharedStyles.xaml'
|
||||
$script:BubbleHintSchema = Join-Path $schemasPath 'BubbleHint.xaml'
|
||||
$script:ImportExportConfigSchema = Join-Path $schemasPath 'ImportExportConfigWindow.xaml'
|
||||
$script:RestoreBackupWindowSchema = Join-Path $schemasPath 'RestoreBackupWindow.xaml'
|
||||
$script:LoadAppsDetailsScriptPath = Join-Path (Join-Path $scriptsPath 'FileIO') 'LoadAppsDetailsFromJson.ps1'
|
||||
|
||||
$script:ControlParams = 'WhatIf', 'Confirm', 'Verbose', 'Debug', 'LogPath', 'Silent', 'Sysprep', 'User', 'NoRestartExplorer', 'RunDefaults', 'RunDefaultsLite', 'RunSavedSettings', 'Config', 'RunAppsListGenerator', 'CLI', 'AppRemovalTarget'
|
||||
|
||||
# Script-level variables for GUI elements
|
||||
$script:GuiWindow = $null
|
||||
@@ -212,29 +214,15 @@ Write-Host ""
|
||||
|
||||
# Log script output to 'Win11Debloat.log' at the specified path
|
||||
if ($LogPath -and (Test-Path $LogPath)) {
|
||||
Start-Transcript -Path "$LogPath/Win11Debloat.log" -Append -IncludeInvocationHeader -Force | Out-Null
|
||||
Start-Transcript -Path (Join-Path $LogPath 'Win11Debloat.log') -Append -IncludeInvocationHeader -Force | Out-Null
|
||||
}
|
||||
else {
|
||||
Start-Transcript -Path $script:DefaultLogPath -Append -IncludeInvocationHeader -Force | Out-Null
|
||||
}
|
||||
|
||||
# Check if script has all required files/directories.
|
||||
$optionalPathVariables = @('SavedSettingsFilePath', 'CustomAppsListFilePath', 'DefaultLogPath')
|
||||
$requiredPathVariables = @(Get-Variable -Scope Script | Where-Object {
|
||||
$_.Name -match '(FilePath|Schema|ScriptPath|RegfilesPath|AssetsPath)$' -and ($optionalPathVariables -notcontains $_.Name)
|
||||
} | Select-Object -ExpandProperty Name)
|
||||
|
||||
$missingRequiredPaths = @()
|
||||
foreach ($variableName in $requiredPathVariables) {
|
||||
$pathValue = Get-Variable -Name $variableName -Scope Script -ValueOnly
|
||||
|
||||
if ([String]::IsNullOrWhiteSpace($pathValue) -or -not (Test-Path $pathValue)) {
|
||||
$missingRequiredPaths += "$variableName => $pathValue"
|
||||
}
|
||||
}
|
||||
|
||||
if ($missingRequiredPaths.Count -gt 0) {
|
||||
Write-Error "Win11Debloat is unable to find required files, please ensure all script files are present. Missing: $($missingRequiredPaths -join '; ')"
|
||||
# Check if script has all required files
|
||||
if (-not ((Test-Path $script:DefaultSettingsFilePath) -and (Test-Path $script:AppsListFilePath) -and (Test-Path $script:RegfilesPath) -and (Test-Path $script:AssetsPath) -and (Test-Path $script:AppSelectionSchema) -and (Test-Path $script:ApplyChangesWindowSchema) -and (Test-Path $script:SharedStylesSchema) -and (Test-Path $script:BubbleHintSchema) -and (Test-Path $script:RestoreBackupWindowSchema) -and (Test-Path $script:FeaturesFilePath))) {
|
||||
Write-Error "Win11Debloat is unable to find required files, please ensure all script files are present"
|
||||
Write-Output ""
|
||||
Write-Output "Press any key to exit..."
|
||||
$null = [System.Console]::ReadKey()
|
||||
@@ -245,15 +233,6 @@ if ($missingRequiredPaths.Count -gt 0) {
|
||||
$script:Features = @{}
|
||||
try {
|
||||
$featuresData = Get-Content -Path $script:FeaturesFilePath -Raw | ConvertFrom-Json
|
||||
|
||||
if (-not $featuresData.Version -or $featuresData.Version -ne $script:FeaturesConfigVersion) {
|
||||
Write-Error "Features.json version mismatch (expected $($script:FeaturesConfigVersion), found $($featuresData.Version))"
|
||||
Write-Output ""
|
||||
Write-Output "Press any key to exit..."
|
||||
$null = [System.Console]::ReadKey()
|
||||
Exit
|
||||
}
|
||||
|
||||
foreach ($feature in $featuresData.Features) {
|
||||
$script:Features[$feature.FeatureId] = $feature
|
||||
}
|
||||
@@ -312,10 +291,17 @@ if (-not $script:WingetInstalled -and -not $Silent) {
|
||||
. "$PSScriptRoot/Scripts/CLI/PrintHeader.ps1"
|
||||
|
||||
# Features functions
|
||||
. "$PSScriptRoot/Scripts/Features/GetCurrentTweakState.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/ExecuteChanges.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/CreateSystemRestorePoint.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/BackupRegistryFeatureSelection.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/BackupRegistrySnapshotCapture.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/BackupRegistryState.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/RegistryBackupValidation.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/RestoreRegistryApplyState.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/RestoreRegistryBackup.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/DisableStoreSearchSuggestions.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/EnableWindowsFeature.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/WindowsOptionalFeatures.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/ImportRegistryFile.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/ReplaceStartMenu.ps1"
|
||||
. "$PSScriptRoot/Scripts/Features/RestartExplorer.ps1"
|
||||
@@ -339,24 +325,37 @@ if (-not $script:WingetInstalled -and -not $Silent) {
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-MessageBox.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-ConfigWindow.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-ApplyModal.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-RevertSettingsModal.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-AppSelectionWindow.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-RestoreBackupWindow.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/RestoreBackupDialogFeatureLists.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-RestoreBackupDialog.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/MainWindow-WindowChrome.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/MainWindow-AppSelection.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/MainWindow-TweaksBuilder.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/MainWindow-Navigation.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/MainWindow-Deployment.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-MainWindow.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-AboutDialog.ps1"
|
||||
. "$PSScriptRoot/Scripts/GUI/Show-Bubble.ps1"
|
||||
|
||||
# Helper functions
|
||||
. "$PSScriptRoot/Scripts/Helpers/AddParameter.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/ResolveUserProfilePath.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/UserHiveHelpers.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/CheckIfUserExists.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/CheckModernStandbySupport.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GenerateAppsList.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GetFriendlyRegistryBackupTarget.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GetFriendlyTargetUserName.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/ImportConfigToParams.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GetTargetUserForAppRemoval.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GetUndoFeatureForParam.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/Get-RegFileOperations.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/Test-TargetUserName.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GetUserDirectory.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/GetUserName.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/TestIfUserIsLoggedIn.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/RegistryPathHelpers.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/ApplyRegistryRegFile.ps1"
|
||||
. "$PSScriptRoot/Scripts/Helpers/ConfirmUnsafeAppRemoval.ps1"
|
||||
|
||||
# Threading functions
|
||||
. "$PSScriptRoot/Scripts/Threading/DoEvents.ps1"
|
||||
@@ -379,6 +378,7 @@ $WinVersion = Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\Current
|
||||
$script:ModernStandbySupported = CheckModernStandbySupport
|
||||
|
||||
$script:Params = $PSBoundParameters
|
||||
$script:UndoParams = @{}
|
||||
|
||||
# Add default Apps parameter when RemoveApps is requested and Apps was not explicitly provided
|
||||
if ((-not $script:Params.ContainsKey("Apps")) -and $script:Params.ContainsKey("RemoveApps")) {
|
||||
@@ -394,27 +394,6 @@ foreach ($Param in $script:ControlParams) {
|
||||
}
|
||||
}
|
||||
|
||||
# Guard: Undo mode requires at least one actionable and cannot be combined with deployment-targeted parameters
|
||||
if ($script:Params.ContainsKey('Undo')) {
|
||||
$deploymentTargetParams = @('Sysprep', 'User', 'AppRemovalTarget')
|
||||
$selectedDeploymentParams = @($deploymentTargetParams | Where-Object { $script:Params.ContainsKey($_) })
|
||||
|
||||
if ($selectedDeploymentParams.Count -gt 0) {
|
||||
Write-Error "The -Undo parameter cannot be combined with deployment target parameters: -$($selectedDeploymentParams -join ', -')."
|
||||
AwaitKeyToExit
|
||||
}
|
||||
|
||||
$loadsSettingsFromPreset = $RunDefaults -or $RunDefaultsLite -or $RunSavedSettings
|
||||
$undoTargets = @($script:Params.Keys | Where-Object {
|
||||
($script:ControlParams -notcontains $_) -and $_ -ne 'Apps' -and $_ -ne 'CreateRestorePoint'
|
||||
})
|
||||
|
||||
if ($undoTargets.Count -eq 0 -and -not $loadsSettingsFromPreset) {
|
||||
Write-Error "The -Undo parameter requires at least one setting/feature parameter to revert."
|
||||
AwaitKeyToExit
|
||||
}
|
||||
}
|
||||
|
||||
# Hide progress bars for app removal, as they block Win11Debloat's output
|
||||
if (-not ($script:Params.ContainsKey("Verbose"))) {
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
@@ -429,7 +408,7 @@ else {
|
||||
}
|
||||
|
||||
if ($script:Params.ContainsKey("Sysprep")) {
|
||||
$defaultUserPath = GetUserDirectory -userName "Default"
|
||||
GetUserDirectory -userName "Default" | Out-Null
|
||||
|
||||
# Exit script if run in Sysprep mode on Windows 10
|
||||
if ($WinVersion -lt 22000) {
|
||||
@@ -440,10 +419,10 @@ if ($script:Params.ContainsKey("Sysprep")) {
|
||||
|
||||
# Ensure that target user exists, if User or AppRemovalTarget parameter was provided
|
||||
if ($script:Params.ContainsKey("User")) {
|
||||
$userPath = GetUserDirectory -userName $script:Params.Item("User")
|
||||
GetUserDirectory -userName $script:Params.Item("User") | Out-Null
|
||||
}
|
||||
if ($script:Params.ContainsKey("AppRemovalTarget")) {
|
||||
$userPath = GetUserDirectory -userName $script:Params.Item("AppRemovalTarget")
|
||||
GetUserDirectory -userName $script:Params.Item("AppRemovalTarget") | Out-Null
|
||||
}
|
||||
|
||||
# Remove LastUsedSettings.json file if it exists and is empty
|
||||
@@ -513,7 +492,7 @@ if ((-not $script:Params.Count) -or $RunDefaults -or $RunDefaultsLite -or $RunSa
|
||||
Exit
|
||||
}
|
||||
catch {
|
||||
Write-Warning "Something went wrong while loading the graphical interface, falling back to CLI mode: $_"
|
||||
Write-Warning "Unable to load WPF GUI (not supported in this environment), falling back to CLI mode"
|
||||
if (-not $Silent) {
|
||||
Write-Host ""
|
||||
Write-Host "Press any key to continue..."
|
||||
@@ -554,17 +533,9 @@ if (($controlParamsCount -eq $script:Params.Keys.Count) -or ($script:Params.Keys
|
||||
AwaitKeyToExit
|
||||
}
|
||||
|
||||
try {
|
||||
# Execute all selected/provided parameters using the consolidated function
|
||||
# (This also handles restore point creation if requested)
|
||||
ExecuteAllChanges
|
||||
}
|
||||
catch {
|
||||
Write-Error "An error occurred while applying changes: $_"
|
||||
|
||||
AwaitKeyToExit
|
||||
}
|
||||
|
||||
# Execute all selected/provided parameters using the consolidated function
|
||||
# (This also handles restore point creation if requested)
|
||||
ExecuteAllChanges
|
||||
|
||||
RestartExplorer
|
||||
|
||||
|
||||
Reference in New Issue
Block a user