undergroundwires / privacy.sexy

Open-source tool to enforce privacy & security best-practices on Windows, macOS and Linux, because privacy is sexy
https://privacy.sexy
GNU Affero General Public License v3.0
4.02k stars 170 forks source link

[BUG]: unable to revert removal of windows security UI (PACKAGE NOT FOUND) #293

Closed boredchilada closed 9 months ago

boredchilada commented 9 months ago

Description

Trying to install "Microsoft.Windows.SecHealthUI" using its package family name: "Microsoft.Windows.SecHealthUI_cw5n1h2txyewy" from system installation...
WARNING: Error installing using package family name: Deployment failed with HRESULT: 0x80073CF1, Package was not
found.

Windows cannot perform the RegisterByPackageFamilyName operation because it could not find
Microsoft.Windows.SecHealthUI_cw5n1h2txyewy in the repository. Make sure Microsoft.Windows.SecHealthUI_cw5n1h2txyewy
has been staged or was installed by another user.

NOTE: For additional information, look for [ActivityId] 116d36f7-2ad9-0007-6007-6e11d92ada01 in the Event Log or use
the command line Get-AppPackageLog -ActivityID 116d36f7-2ad9-0007-6007-6e11d92ada01
Unable to reinstall the requested package (Microsoft.Windows.SecHealthUI). It appears to no longer be included in this
version of Windows. You may search for it or an alternative in the Microsoft Store or consider using an earlier
version of Windows where this package was originally provided.
At line:1 char:2143
+ ... ssage)"; }; throw "Unable to reinstall the requested package ($packag ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Unable to reins...nally provided.:String) [], RuntimeException
    + FullyQualifiedErrorId : Unable to reinstall the requested package (Microsoft.Windows.SecHealthUI). It appears to
    no longer be included in this version of Windows. You may search for it or an alternative in the Microsoft Store
  or consider using an earlier version of Windows where this package was originally provided.

OS

image

Reproduction steps

image

Scripts

image

Screenshots

image image

Additional information

boredchilada commented 9 months ago

https://techcommunity.microsoft.com/t5/windows-insider-program/windows-11-s-windows-security-app-can-t-open/m-p/2709944

these dont work either

undergroundwires commented 9 months ago

Hi, security app in Windows 11 is not supported on public version, but I added the support this week and it will be released in next patch so security app can be properly deleted/restored.

privacy.sexy version that's up now can only delete and restore security app for Windows 10. So privacy.sexy did not delete your security app because it's unable to do so for Windows 11. There are two options

  1. You used some other tool? I'd like to know in that case because I did not know of any other tool that does similar stuff.
  2. There's a side-effect going on. Another script that's unrelated is causing the issue you have. If you did not run any other tool please share full code for the script you executed so we can debug this.

On Windows 10, this package is named Microsoft.Windows.SecHealthUI, on Windows 11 it's named Microsoft.SecHealthUI. When you run revert code for Windows 10 version, it tries the locate that package that does not exist in W11 and show error, but this is OK and expected.

The code I share now is from the latest version of privacy.sexy, that's not yet released but you can build it from source code if you wish. This will remove and restore both W10 and W11 apps. It will first show the error for W10 app because it will not find it on your system (just like in your screenshot), and it's OK. It will then try to restore W11 security app which is relevant for you.

remove-windows-security-app.bat ```batchfile @echo off :: https://privacy.sexy — v0.12.8 — Sat, 09 Dec 2023 20:57:49 GMT :: Ensure admin privileges fltmc >nul 2>&1 || ( echo Administrator privileges are required. PowerShell Start -Verb RunAs '%0' 2> nul || ( echo Right-click on the script and select "Run as administrator". pause & exit 1 ) exit 0 ) :: Initialize environment setlocal EnableExtensions DisableDelayedExpansion :: Remove "Windows Security" app (`SecHealthUI`) (breaks Windows Security user interface) echo --- Remove "Windows Security" app (`SecHealthUI`) (breaks Windows Security user interface) :: Soft delete files matching pattern (with additional permissions) : "%WINDIR%\SystemApps\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%WINDIR%\SystemApps\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Soft delete files matching pattern (with additional permissions) : "%WINDIR%\$(("Microsoft.Windows.SecHealthUI" -Split '\.')[-1])\*" PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%WINDIR%\$(("^""Microsoft.Windows.SecHealthUI"^"" -Split '\.')[-1])\*"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Soft delete files matching pattern (with additional permissions) : "%SYSTEMDRIVE%\Program Files\WindowsApps\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%SYSTEMDRIVE%\Program Files\WindowsApps\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Enable removal of system app 'Microsoft.Windows.SecHealthUI' by marking it as "EndOfLife" PowerShell -ExecutionPolicy Unrestricted -Command "$keyName='HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\EndOfLife\$CURRENT_USER_SID\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy'; $replaceSid=$true <# $false #>; $registryHive = $keyName.Split('\')[0]; $registryPath = "^""$($registryHive):$($keyName.Substring($registryHive.Length))"^""; $userSid = (New-Object System.Security.Principal.NTAccount($env:USERNAME)).Translate([Security.Principal.SecurityIdentifier]).Value; $registryPath = $registryPath.Replace('$CURRENT_USER_SID', $userSid); if (Test-Path $registryPath) {; Write-Host "^""Skipping, no action needed, registry path `"^""$registryPath`"^"" already exists."^""; exit 0; }; try {; New-Item -Path $registryPath -Force -ErrorAction Stop | Out-Null; Write-Host "^""Successfully created the registry key at path `"^""$registryPath`"^""."^""; } catch {; Write-Error "^""Failed to create the registry key at path `"^""$registryPath`"^"": $($_.Exception.Message)"^""; }" :: Uninstall 'Microsoft.Windows.SecHealthUI' Microsoft Store app. PowerShell -ExecutionPolicy Unrestricted -Command "Get-AppxPackage 'Microsoft.Windows.SecHealthUI' | Remove-AppxPackage" :: Mark 'Microsoft.Windows.SecHealthUI' as deprovisioned to block reinstall during Windows updates. reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deprovisioned\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy" /f :: Revert 'Microsoft.Windows.SecHealthUI' to its default, non-removable state. PowerShell -ExecutionPolicy Unrestricted -Command "$keyName='HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\EndOfLife\$CURRENT_USER_SID\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy'; $replaceSid=$true <# $false #>; $registryHive = $keyName.Split('\')[0]; $registryPath = "^""$($registryHive):$($keyName.Substring($registryHive.Length))"^""; $userSid = (New-Object System.Security.Principal.NTAccount($env:USERNAME)).Translate([Security.Principal.SecurityIdentifier]).Value; $registryPath = $registryPath.Replace('$CURRENT_USER_SID', $userSid); if (-not (Test-Path $registryPath)) {; Write-Host "^""Skipping, no action needed, registry path `"^""$registryPath`"^"" does not exist."^""; exit 0; }; try {; Remove-Item -Path $registryPath -Force -ErrorAction Stop | Out-Null; Write-Host "^""Successfully removed the registry key at path `"^""$registryPath`"^""."^""; } catch {; Write-Error "^""Failed to remove the registry key at path `"^""$registryPath`"^"": $($_.Exception.Message)"^""; }" :: Soft delete files matching pattern : "%LOCALAPPDATA%\Packages\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%LOCALAPPDATA%\Packages\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }" :: Soft delete files matching pattern (with additional permissions) : "%PROGRAMDATA%\Microsoft\Windows\AppRepository\Packages\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%PROGRAMDATA%\Microsoft\Windows\AppRepository\Packages\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Enable removal of system app 'Microsoft.SecHealthUI' by marking it as "EndOfLife" PowerShell -ExecutionPolicy Unrestricted -Command "$keyName='HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\EndOfLife\$CURRENT_USER_SID\Microsoft.SecHealthUI_8wekyb3d8bbwe'; $replaceSid=$true <# $false #>; $registryHive = $keyName.Split('\')[0]; $registryPath = "^""$($registryHive):$($keyName.Substring($registryHive.Length))"^""; $userSid = (New-Object System.Security.Principal.NTAccount($env:USERNAME)).Translate([Security.Principal.SecurityIdentifier]).Value; $registryPath = $registryPath.Replace('$CURRENT_USER_SID', $userSid); if (Test-Path $registryPath) {; Write-Host "^""Skipping, no action needed, registry path `"^""$registryPath`"^"" already exists."^""; exit 0; }; try {; New-Item -Path $registryPath -Force -ErrorAction Stop | Out-Null; Write-Host "^""Successfully created the registry key at path `"^""$registryPath`"^""."^""; } catch {; Write-Error "^""Failed to create the registry key at path `"^""$registryPath`"^"": $($_.Exception.Message)"^""; }" :: Uninstall 'Microsoft.SecHealthUI' Microsoft Store app. PowerShell -ExecutionPolicy Unrestricted -Command "Get-AppxPackage 'Microsoft.SecHealthUI' | Remove-AppxPackage" :: Mark 'Microsoft.SecHealthUI' as deprovisioned to block reinstall during Windows updates. reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deprovisioned\Microsoft.SecHealthUI_8wekyb3d8bbwe" /f :: Revert 'Microsoft.SecHealthUI' to its default, non-removable state. PowerShell -ExecutionPolicy Unrestricted -Command "$keyName='HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\EndOfLife\$CURRENT_USER_SID\Microsoft.SecHealthUI_8wekyb3d8bbwe'; $replaceSid=$true <# $false #>; $registryHive = $keyName.Split('\')[0]; $registryPath = "^""$($registryHive):$($keyName.Substring($registryHive.Length))"^""; $userSid = (New-Object System.Security.Principal.NTAccount($env:USERNAME)).Translate([Security.Principal.SecurityIdentifier]).Value; $registryPath = $registryPath.Replace('$CURRENT_USER_SID', $userSid); if (-not (Test-Path $registryPath)) {; Write-Host "^""Skipping, no action needed, registry path `"^""$registryPath`"^"" does not exist."^""; exit 0; }; try {; Remove-Item -Path $registryPath -Force -ErrorAction Stop | Out-Null; Write-Host "^""Successfully removed the registry key at path `"^""$registryPath`"^""."^""; } catch {; Write-Error "^""Failed to remove the registry key at path `"^""$registryPath`"^"": $($_.Exception.Message)"^""; }" :: ---------------------------------------------------------- :: Pause the script to view the final state pause :: Restore previous environment settings endlocal :: Exit the script successfully exit /b 0 ```

This is what you're looking for:

revert-windows-security-app.bat ```batchfile @echo off :: https://privacy.sexy — v0.12.8 — Sat, 09 Dec 2023 20:57:49 GMT :: Ensure admin privileges fltmc >nul 2>&1 || ( echo Administrator privileges are required. PowerShell Start -Verb RunAs '%0' 2> nul || ( echo Right-click on the script and select "Run as administrator". pause & exit 1 ) exit 0 ) :: Initialize environment setlocal EnableExtensions DisableDelayedExpansion :: Remove "Windows Security" app (`SecHealthUI`) (breaks Windows Security user interface) (revert) echo --- Remove "Windows Security" app (`SecHealthUI`) (breaks Windows Security user interface) (revert) :: Restore files matching pattern (with additional permissions) : "%WINDIR%\SystemApps\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%WINDIR%\SystemApps\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*.OLD"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Restore files matching pattern (with additional permissions) : "%WINDIR%\$(("Microsoft.Windows.SecHealthUI" -Split '\.')[-1])\*" PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%WINDIR%\$(("^""Microsoft.Windows.SecHealthUI"^"" -Split '\.')[-1])\*.OLD"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Restore files matching pattern (with additional permissions) : "%SYSTEMDRIVE%\Program Files\WindowsApps\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%SYSTEMDRIVE%\Program Files\WindowsApps\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*.OLD"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Reinstall 'Microsoft.Windows.SecHealthUI' if it was previously uninstalled. PowerShell -ExecutionPolicy Unrestricted -Command "$packageName='Microsoft.Windows.SecHealthUI'; $publisherId='cw5n1h2txyewy'; if (Get-AppxPackage -Name $packageName) {; Write-Host "^""Skipping, `"^""$packageName`"^"" is already installed for the current user."^""; exit 0; }; Write-Host "^""Starting the installation process for `"^""$packageName`"^""..."^""; <# Attempt installation using the manifest file #>; Write-Host "^""Checking if `"^""$packageName`"^"" is installed on another user profile..."^""; $packages = @(Get-AppxPackage -AllUsers $packageName); if (!$packages) {; Write-Host "^""`"^""$packageName`"^"" is not installed on any other user profiles."^""; } else {; foreach ($package in $packages) {; Write-Host "^""Found package `"^""$($package.PackageFullName)`"^""."^""; $installationDir = $package.InstallLocation; if ([string]::IsNullOrWhiteSpace($installationDir)) {; Write-Warning "^""Installation directory for `"^""$packageName`"^"" is not found or invalid."^""; continue; }; $manifestPath = Join-Path -Path $installationDir -ChildPath 'AppxManifest.xml'; try {; if (-Not (Test-Path "^""$manifestPath"^"")) {; Write-Host "^""Manifest file not found for `"^""$packageName`"^"" on another user profile: `"^""$manifestPath`"^""."^""; continue; }; } catch {; Write-Warning "^""An error occurred while checking for the manifest file: $($_.Exception.Message)"^""; continue; }; Write-Host "^""Manifest file located. Trying to install using the manifest: `"^""$manifestPath`"^""..."^""; try {; Add-AppxPackage -DisableDevelopmentMode -Register "^""$manifestPath"^"" -ErrorAction Stop; Write-Host "^""Successfully installed `"^""$packageName`"^"" using its manifest file."^""; exit 0; } catch {; Write-Warning "^""Error installing from manifest: $($_.Exception.Message)"^""; }; }; }; <# Attempt installation using the package family name #>; $packageFamilyName = "^""$($packageName)_$($publisherId)"^""; Write-Host "^""Trying to install `"^""$packageName`"^"" using its package family name: `"^""$packageFamilyName`"^"" from system installation..."^""; try {; Add-AppxPackage -RegisterByFamilyName -MainPackage $packageFamilyName -ErrorAction Stop; Write-Host "^""Successfully installed `"^""$packageName`"^"" using its package family name."^""; exit 0; } catch {; Write-Warning "^""Error installing using package family name: $($_.Exception.Message)"^""; }; throw "^""Unable to reinstall the requested package ($packageName). "^"" + "^""It appears to no longer be included in this version of Windows. "^"" + "^""You may search for it or an alternative in the Microsoft Store or "^"" + "^""consider using an earlier version of Windows where this package was originally provided."^""" :: Remove 'Microsoft.Windows.SecHealthUI' from deprovisioned list to allow reinstall during updates. reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deprovisioned\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy" /f 2>nul :: Restore files matching pattern : "%LOCALAPPDATA%\Packages\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%LOCALAPPDATA%\Packages\Microsoft.Windows.SecHealthUI_cw5n1h2txyewy\*.OLD"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }" :: Restore files matching pattern (with additional permissions) : "%PROGRAMDATA%\Microsoft\Windows\AppRepository\Packages\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*" PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%PROGRAMDATA%\Microsoft\Windows\AppRepository\Packages\Microsoft.Windows.SecHealthUI_*_cw5n1h2txyewy\*.OLD"^""; $expandedPath = [System.Environment]::ExpandEnvironmentVariables($pathGlobPattern); Write-Host "^""Searching for items matching pattern: `"^""$($expandedPath)`"^""."^""; $renamedCount = 0; $skippedCount = 0; $failedCount = 0; Add-Type -TypeDefinition "^""using System;`r`nusing System.Runtime.InteropServices;`r`npublic class Privileges {`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,`r`n ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);`r`n [DllImport(`"^""advapi32.dll`"^"", ExactSpelling = true, SetLastError = true)]`r`n internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);`r`n [DllImport(`"^""advapi32.dll`"^"", SetLastError = true)]`r`n internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);`r`n [StructLayout(LayoutKind.Sequential, Pack = 1)]`r`n internal struct TokPriv1Luid {`r`n public int Count;`r`n public long Luid;`r`n public int Attr;`r`n }`r`n internal const int SE_PRIVILEGE_ENABLED = 0x00000002;`r`n internal const int TOKEN_QUERY = 0x00000008;`r`n internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;`r`n public static bool AddPrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = SE_PRIVILEGE_ENABLED;`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n public static bool RemovePrivilege(string privilege) {`r`n try {`r`n bool retVal;`r`n TokPriv1Luid tp;`r`n IntPtr hproc = GetCurrentProcess();`r`n IntPtr htok = IntPtr.Zero;`r`n retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);`r`n tp.Count = 1;`r`n tp.Luid = 0;`r`n tp.Attr = 0; // This line is changed to revoke the privilege`r`n retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);`r`n retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);`r`n return retVal;`r`n } catch (Exception ex) {`r`n throw new Exception(`"^""Failed to adjust token privileges`"^"", ex);`r`n }`r`n }`r`n [DllImport(`"^""kernel32.dll`"^"", CharSet = CharSet.Auto)]`r`n public static extern IntPtr GetCurrentProcess();`r`n}"^""; [Privileges]::AddPrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::AddPrivilege('SeTakeOwnershipPrivilege') | Out-Null; $adminSid = New-Object System.Security.Principal.SecurityIdentifier 'S-1-5-32-544'; $adminAccount = $adminSid.Translate([System.Security.Principal.NTAccount]); $adminFullControlAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule( $adminAccount, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow ); $foundAbsolutePaths = @(); Write-Host 'Iterating files and directories recursively.'; try {; $foundAbsolutePaths += @(; Get-ChildItem -Path $expandedPath -Force -Recurse -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; try {; $foundAbsolutePaths += @(; Get-Item -Path $expandedPath -ErrorAction Stop | Select-Object -ExpandProperty FullName; ); } catch [System.Management.Automation.ItemNotFoundException] {; <# Swallow, do not run `Test-Path` before, it's unreliable for globs requiring extra permissions #>; }; $foundAbsolutePaths = $foundAbsolutePaths | Select-Object -Unique | Sort-Object -Property { $_.Length } -Descending; if (!$foundAbsolutePaths) {; Write-Host 'Skipping, no items available.'; exit 0; }; Write-Host "^""Initiating processing of $($foundAbsolutePaths.Count) items from `"^""$expandedPath`"^""."^""; foreach ($path in $foundAbsolutePaths) {; if (Test-Path -Path $path -PathType Container) {; Write-Host "^""Skipping folder (not its contents): `"^""$path`"^""."^""; $skippedCount++; continue; }; if($revert -eq $true) {; if (-not $path.EndsWith('.OLD')) {; Write-Host "^""Skipping non-backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; } else {; if ($path.EndsWith('.OLD')) {; Write-Host "^""Skipping backup file: `"^""$path`"^""."^""; $skippedCount++; continue; }; }; $originalFilePath = $path; Write-Host "^""Processing file: `"^""$originalFilePath`"^""."^""; if (-Not (Test-Path $originalFilePath)) {; Write-Host "^""Skipping, file `"^""$originalFilePath`"^"" not found."^""; $skippedCount++; exit 0; }; $originalAcl = Get-Acl -Path "^""$originalFilePath"^""; $accessGranted = $false; try {; $acl = Get-Acl -Path "^""$originalFilePath"^""; $acl.SetOwner($adminAccount) <# Take Ownership (because file is owned by TrustedInstaller) #>; $acl.AddAccessRule($adminFullControlAccessRule) <# Grant rights to be able to move the file #>; Set-Acl -Path $originalFilePath -AclObject $acl -ErrorAction Stop; $accessGranted = $true; } catch {; Write-Warning "^""Failed to grant access to `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; if ($revert -eq $true) {; $newFilePath = $originalFilePath.Substring(0, $originalFilePath.Length - 4); } else {; $newFilePath = "^""$($originalFilePath).OLD"^""; }; try {; Move-Item -LiteralPath "^""$($originalFilePath)"^"" -Destination "^""$newFilePath"^"" -Force -ErrorAction Stop; Write-Host "^""Successfully processed `"^""$originalFilePath`"^""."^""; $renamedCount++; if ($accessGranted) {; try {; Set-Acl -Path $newFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; }; }; } catch {; Write-Error "^""Failed to rename `"^""$originalFilePath`"^"" to `"^""$newFilePath`"^"": $($_.Exception.Message)"^""; $failedCount++; if ($accessGranted) {; try {; Set-Acl -Path $originalFilePath -AclObject $originalAcl -ErrorAction Stop; } catch {; Write-Warning "^""Failed to restore access on `"^""$originalFilePath`"^"": $($_.Exception.Message)"^""; }; }; }; }; if (($renamedCount -gt 0) -or ($skippedCount -gt 0)) {; Write-Host "^""Successfully processed $renamedCount items and skipped $skippedCount items."^""; }; if ($failedCount -gt 0) {; Write-Warning "^""Failed to processed $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null" :: Reinstall 'Microsoft.SecHealthUI' if it was previously uninstalled. PowerShell -ExecutionPolicy Unrestricted -Command "$packageName='Microsoft.SecHealthUI'; $publisherId='8wekyb3d8bbwe'; if (Get-AppxPackage -Name $packageName) {; Write-Host "^""Skipping, `"^""$packageName`"^"" is already installed for the current user."^""; exit 0; }; Write-Host "^""Starting the installation process for `"^""$packageName`"^""..."^""; <# Attempt installation using the manifest file #>; Write-Host "^""Checking if `"^""$packageName`"^"" is installed on another user profile..."^""; $packages = @(Get-AppxPackage -AllUsers $packageName); if (!$packages) {; Write-Host "^""`"^""$packageName`"^"" is not installed on any other user profiles."^""; } else {; foreach ($package in $packages) {; Write-Host "^""Found package `"^""$($package.PackageFullName)`"^""."^""; $installationDir = $package.InstallLocation; if ([string]::IsNullOrWhiteSpace($installationDir)) {; Write-Warning "^""Installation directory for `"^""$packageName`"^"" is not found or invalid."^""; continue; }; $manifestPath = Join-Path -Path $installationDir -ChildPath 'AppxManifest.xml'; try {; if (-Not (Test-Path "^""$manifestPath"^"")) {; Write-Host "^""Manifest file not found for `"^""$packageName`"^"" on another user profile: `"^""$manifestPath`"^""."^""; continue; }; } catch {; Write-Warning "^""An error occurred while checking for the manifest file: $($_.Exception.Message)"^""; continue; }; Write-Host "^""Manifest file located. Trying to install using the manifest: `"^""$manifestPath`"^""..."^""; try {; Add-AppxPackage -DisableDevelopmentMode -Register "^""$manifestPath"^"" -ErrorAction Stop; Write-Host "^""Successfully installed `"^""$packageName`"^"" using its manifest file."^""; exit 0; } catch {; Write-Warning "^""Error installing from manifest: $($_.Exception.Message)"^""; }; }; }; <# Attempt installation using the package family name #>; $packageFamilyName = "^""$($packageName)_$($publisherId)"^""; Write-Host "^""Trying to install `"^""$packageName`"^"" using its package family name: `"^""$packageFamilyName`"^"" from system installation..."^""; try {; Add-AppxPackage -RegisterByFamilyName -MainPackage $packageFamilyName -ErrorAction Stop; Write-Host "^""Successfully installed `"^""$packageName`"^"" using its package family name."^""; exit 0; } catch {; Write-Warning "^""Error installing using package family name: $($_.Exception.Message)"^""; }; throw "^""Unable to reinstall the requested package ($packageName). "^"" + "^""It appears to no longer be included in this version of Windows. "^"" + "^""You may search for it or an alternative in the Microsoft Store or "^"" + "^""consider using an earlier version of Windows where this package was originally provided."^""" :: Remove 'Microsoft.SecHealthUI' from deprovisioned list to allow reinstall during updates. reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Appx\AppxAllUserStore\Deprovisioned\Microsoft.SecHealthUI_8wekyb3d8bbwe" /f 2>nul :: ---------------------------------------------------------- :: Pause the script to view the final state pause :: Restore previous environment settings endlocal :: Exit the script successfully exit /b 0 ```
boredchilada commented 9 months ago

Gotcha, it is quite possible i ran one of the below tools i think i ran this one https://github.com/ionuttbara/windows-defender-remover or https://github.com/LeDragoX/Win-Debloat-Tools

more likely the first one but i've noticed that it seems to remove/disable stuff at the surface while the backend is still active type of thing.

ive since reinstalled windows and took a more methodical approach as the first go around i didn't keep track of what scripts i used :P. i've avoided disabling the winsec ui etc and everything seems to be working well so far.

undergroundwires commented 9 months ago

Thank you for the context @boredchilada. Windows 11 app removal/revert is added in 0.12.9 🚀 Let me know if you encounter anything else in future.