Skip to main content

Disable Defender for Endpoint remote configuration

Overview

About this script

This script improves your privacy on Windows.

These changes use Windows system commands to update your settings.

This script disables remote configuration for Microsoft Defender for Endpoint, enhancing privacy and local control over your device's security settings.

Microsoft Defender for Endpoint is a security suite designed to protect devices from cyber threats 1. Some components are included by default on Windows without requiring user opt-in 2 3. Remote configuration allows administrators to manage and update settings across multiple devices. This feature is typically used in work or school environments where centralized control of multiple devices is necessary.

Disabling this feature enhances privacy by preventing remote changes to your Defender for Endpoint settings. It may also improve system performance by reducing background processes related to remote management.

However, disabling this feature may:

  • Prevent automatic security updates from being applied.
  • Limit the ability of IT administrators to manage security settings across devices.
  • Violate your organization's compliance policies if you're on a work or school computer.
Caution

Disabling this feature may reduce your device's security and limit automatic security adjustments.

Technical Details

This script disables the following components:

  • Windows Defender Advanced Threat Protection CSP 2 (CLSID: FEEE9C23-C4E2-4A34-8C73-FE8F9786C8B4 2)
  • Windows Defender Advanced Threat Protection Manageability module 3 (Path: %PROGRAMFILES%\Windows Defender Advanced Threat Protection\WATPCSP.dll 2 3)

For detailed configurations and settings, refer to Microsoft's documentation on WindowsAdvancedThreatProtection CSP 4.

This script uses Batch (batchfile) scripting language.

Use with Caution

This script is only recommended if you understand its implications. Some non-critical or features may no longer function correctly after running this script.

Implementation Details
  • Language: batch

  • Required Privileges: Administrator rights

  • Compatibility: Windows only

  • Reversibility: Can be undone using provided revert script

Explore Categories

This action belongs to Disable Defender for Endpoint category. This category provides scripts to disable Defender for Endpoint, a security platform that impacts user privacy. Defender for Endpoint is officially known as Microsoft Defender for Endpoint. It was previously called Microsoft Defender Advanced Threat Protection (ATP). It is designed to... Read more on category page ▶

Apply now

Choose one of three ways to apply:

  1. Automatically via privacy.sexy: The easiest and safest option.
  2. Manually by downloading: Requires downloading a file.
  3. Manually by copying: Advanced flexibility.

Alternative 1. Apply with Privacy.sexy

privacy.sexy is free and open-source application that lets securely apply this action easily.

Open privacy.sexy

You can fully restore this action (revert back to the original behavior) using the application.

privacy.sexy instructions
  1. Open or download the desktop application
  2. Search for the script name: Disable Defender for Endpoint remote configuration.
  3. Check the script by clicking on the checkbox.
  4. Click on Run button at the bottom of the page.

Alternative 2. Download

Irreversible Changes

This script is irreversible, meaning there is no straightforward method to restore changes once applied. Exercise caution before running, restoring it may not be possible.

  1. Download the script file by clicking on the button below:

    Download script

  2. Run the script file by clicking on it.

Download revert script

This file restores your system to its original state, before this script is applied.

Download restore script

Alternative 3. Copy

This is for advanced users. Consider automatically applying or downloading the script for simpler way.

  1. Open Command Prompt as administrator.
HELP: Step-by-step guide
  1. Click on Start menu

  2. Type cmd

  3. Right click on Command Prompt select Run as administrator

  4. Click on Yes to run Command Prompt


Animation showing how to open terminal as administrator on Windows 11

  1. Copy the following code:
Code to apply changes
:: Soft-delete the registry key: HKLM\Software\Classes\CLSID\{FEEE9C23-C4E2-4A34-8C73-FE8F9786C8B4} as TrustedInstaller
PowerShell -ExecutionPolicy Unrestricted -Command "function Invoke-AsTrustedInstaller($Script) { $principalSid = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'); $principalName = $principalSid.Translate([System.Security.Principal.NTAccount]); $streamFile = New-TemporaryFile; $scriptFile = New-TemporaryFile; try { $scriptFile = Rename-Item -LiteralPath $scriptFile -NewName ($scriptFile.BaseName + '.ps1') -Force -PassThru; $Script | Out-File $scriptFile -Encoding UTF8; $taskName = "^""privacy$([char]0x002E)sexy invoke"^""; schtasks.exe /delete /tn $taskName /f 2>&1 | Out-Null; $executionCommand = "^""powershell.exe -ExecutionPolicy Bypass -File '$scriptFile' *>&1 | Out-File -FilePath '$streamFile' -Encoding UTF8"^""; $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "^""-ExecutionPolicy Bypass -Command `"^""$executionCommand`"^"""^""; $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries; Register-ScheduledTask -TaskName $taskName -Action $action -Settings $settings -Force -ErrorAction Stop | Out-Null; try { ($scheduleService = New-Object -ComObject Schedule.Service).Connect(); $scheduleService.GetFolder('\').GetTask($taskName).RunEx($null, 0, 0, $principalName) | Out-Null; $timeout = (Get-Date).AddMinutes(5); Write-Host "^""Running as $principalName"^""; while ((Get-ScheduledTaskInfo $taskName).LastTaskResult -eq 267009) { Start-Sleep -Milliseconds 200; if ((Get-Date) -gt $timeout) { Write-Warning 'Skipping: Timeout'; break; }; }; if (($result = (Get-ScheduledTaskInfo $taskName).LastTaskResult) -ne 0) { Write-Error "^""Failed, due to exit code: $result."^""; } } finally { schtasks.exe /delete /tn $taskName /f | Out-Null; }; Get-Content $streamFile } finally { Remove-Item $streamFile, $scriptFile; }; }; $cmd = 'function Copy-Acl($Src, $Dst) {'+"^""`r`n"^""+' $srcKeys = @(Get-ChildItem -LiteralPath $Src -ErrorAction SilentlyContinue)'+"^""`r`n"^""+' foreach ($key in $srcKeys) {'+"^""`r`n"^""+' $dstKey = Join-Path $Dst $key.PSChildName'+"^""`r`n"^""+' Copy-Acl -Src $key.PSPath -Dst $dstKey'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $acl = Get-Acl -Path $Src -ErrorAction Stop'+"^""`r`n"^""+' $sections = [System.Security.AccessControl.AccessControlSections]::All -band (-bnot [System.Security.AccessControl.AccessControlSections]::Owner)'+"^""`r`n"^""+' $sddl = $acl.GetSecurityDescriptorSddlForm($sections)'+"^""`r`n"^""+' $acl.SetSecurityDescriptorSddlForm($sddl, $sections)'+"^""`r`n"^""+' Set-Acl -Path $Dst -AclObject $acl -ErrorAction Stop'+"^""`r`n"^""+'}'+"^""`r`n"^""+'function Rename-KeyWithAcl($Old, $New) {'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Copy-Item -LiteralPath $Old -Destination $New -Recurse -Force -ErrorAction Stop'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' throw "^""Failed to copy: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Copy-Acl -Src $Old -Dst $New'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to copy ACL: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Remove-Item -LiteralPath $Old -Force -Recurse -ErrorAction Stop | Out-Null'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Remove-Item -LiteralPath $New -Force -Recurse -ErrorAction Stop | Out-Null'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to clean up: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' throw "^""Failed to remove: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'+"^""`r`n"^""+'$rawPath=''HKLM\Software\Classes\CLSID\{FEEE9C23-C4E2-4A34-8C73-FE8F9786C8B4}'''+"^""`r`n"^""+'$suffix=''.OLD'''+"^""`r`n"^""+'$global:ok = 0'+"^""`r`n"^""+'$global:skip = 0'+"^""`r`n"^""+'$global:fail = 0'+"^""`r`n"^""+'function Rename-KeyTree($Path) {'+"^""`r`n"^""+' Write-Host "^""Processing key: $Path"^""'+"^""`r`n"^""+' if (-Not (Test-Path -LiteralPath $Path)) {'+"^""`r`n"^""+' Write-Host ''Skipping: Key does not exist.'''+"^""`r`n"^""+' $global:skip++'+"^""`r`n"^""+' return'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $values = (Get-Item -LiteralPath $Path -ErrorAction Stop | Select-Object -ExpandProperty Property)'+"^""`r`n"^""+' foreach ($value in $values) {'+"^""`r`n"^""+' Write-Host "^""Renaming ''$value''"^""'+"^""`r`n"^""+' if ($value.EndsWith($suffix)) {'+"^""`r`n"^""+' Write-Host ''Skipping: Has suffix.'''+"^""`r`n"^""+' $global:skip++'+"^""`r`n"^""+' continue'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $backupName = $value + $suffix'+"^""`r`n"^""+' Write-Host "^""Renaming to ''$backupName''."^""'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Rename-ItemProperty -LiteralPath $Path -Name $value -NewName $backupName -ErrorAction Stop'+"^""`r`n"^""+' Write-Host ''Successfully renamed.'''+"^""`r`n"^""+' $global:ok++'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to rename value: $_"^""'+"^""`r`n"^""+' $global:fail++'+"^""`r`n"^""+' }'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $subkeys = @(Get-ChildItem -LiteralPath $Path -ErrorAction SilentlyContinue)'+"^""`r`n"^""+' foreach ($key in $subkeys) {'+"^""`r`n"^""+' Rename-KeyTree $key.PSPath'+"^""`r`n"^""+' }'+"^""`r`n"^""+' Write-Host "^""Renaming key ''$Path''."^""'+"^""`r`n"^""+' if ($Path.EndsWith($suffix)) {'+"^""`r`n"^""+' Write-Host ''Skipping: Has suffix.'''+"^""`r`n"^""+' $global:skip++'+"^""`r`n"^""+' } else {'+"^""`r`n"^""+' $backupPath = $Path + $suffix'+"^""`r`n"^""+' while (Test-Path -LiteralPath $backupPath) {'+"^""`r`n"^""+' $backupPath += $suffix'+"^""`r`n"^""+' }'+"^""`r`n"^""+' Write-Host "^""Renaming to ''$backupPath''."^""'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Rename-KeyWithAcl -Old $Path -New $backupPath -ErrorAction Stop'+"^""`r`n"^""+' Write-Host ''Successfully renamed.'''+"^""`r`n"^""+' $global:ok++'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to rename: $_"^""'+"^""`r`n"^""+' $global:fail++'+"^""`r`n"^""+' }'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'+"^""`r`n"^""+'Write-Host "^""Soft deleting registry key ''$rawPath'' recursively."^""'+"^""`r`n"^""+'$hive = $rawPath.Split(''\'')[0]'+"^""`r`n"^""+'$path = $hive + '':'' + $rawPath.Substring($hive.Length)'+"^""`r`n"^""+'Rename-KeyTree $path'+"^""`r`n"^""+'$totalItems = $global:ok + $global:skip + $global:fail'+"^""`r`n"^""+'Write-Host "^""Total items: $totalItems, Renamed: $global:ok, Skipped: $global:skip, Failed: $global:fail"^""'+"^""`r`n"^""+'if (($totalItems -eq 0) -or ($totalItems -eq $global:skip)) {'+"^""`r`n"^""+' Write-Host ''No items were processed. The operation had no effect.'''+"^""`r`n"^""+'} elseif ($global:fail -eq $totalItems) {'+"^""`r`n"^""+' throw "^""Operation failed. All $global:fail items could not be processed."^""'+"^""`r`n"^""+'} elseif ($global:ok) {'+"^""`r`n"^""+' Write-Host "^""Successfully processed $global:ok item(s)."^""'+"^""`r`n"^""+'}'; Invoke-AsTrustedInstaller $cmd"
:: Soft delete files matching pattern: "%PROGRAMFILES%\Windows Defender Advanced Threat Protection\WATPCSP.dll" with additional permissions
PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%PROGRAMFILES%\Windows Defender Advanced Threat Protection\WATPCSP.dll"^""; $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 = @(); 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 process $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null"
  1. Right click on command prompt to paste it.
  2. Press Enter to apply remaining code.

Copy restore code

Copy and run the following code to restore changes:

Revert code
:: Restore registry key: HKLM\Software\Classes\CLSID\{FEEE9C23-C4E2-4A34-8C73-FE8F9786C8B4} as TrustedInstaller
PowerShell -ExecutionPolicy Unrestricted -Command "function Invoke-AsTrustedInstaller($Script) { $principalSid = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'); $principalName = $principalSid.Translate([System.Security.Principal.NTAccount]); $streamFile = New-TemporaryFile; $scriptFile = New-TemporaryFile; try { $scriptFile = Rename-Item -LiteralPath $scriptFile -NewName ($scriptFile.BaseName + '.ps1') -Force -PassThru; $Script | Out-File $scriptFile -Encoding UTF8; $taskName = "^""privacy$([char]0x002E)sexy invoke"^""; schtasks.exe /delete /tn $taskName /f 2>&1 | Out-Null; $executionCommand = "^""powershell.exe -ExecutionPolicy Bypass -File '$scriptFile' *>&1 | Out-File -FilePath '$streamFile' -Encoding UTF8"^""; $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "^""-ExecutionPolicy Bypass -Command `"^""$executionCommand`"^"""^""; $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries; Register-ScheduledTask -TaskName $taskName -Action $action -Settings $settings -Force -ErrorAction Stop | Out-Null; try { ($scheduleService = New-Object -ComObject Schedule.Service).Connect(); $scheduleService.GetFolder('\').GetTask($taskName).RunEx($null, 0, 0, $principalName) | Out-Null; $timeout = (Get-Date).AddMinutes(5); Write-Host "^""Running as $principalName"^""; while ((Get-ScheduledTaskInfo $taskName).LastTaskResult -eq 267009) { Start-Sleep -Milliseconds 200; if ((Get-Date) -gt $timeout) { Write-Warning 'Skipping: Timeout'; break; }; }; if (($result = (Get-ScheduledTaskInfo $taskName).LastTaskResult) -ne 0) { Write-Error "^""Failed, due to exit code: $result."^""; } } finally { schtasks.exe /delete /tn $taskName /f | Out-Null; }; Get-Content $streamFile } finally { Remove-Item $streamFile, $scriptFile; }; }; $cmd = 'function Copy-Acl($Src, $Dst) {'+"^""`r`n"^""+' $srcKeys = @(Get-ChildItem -LiteralPath $Src -ErrorAction SilentlyContinue)'+"^""`r`n"^""+' foreach ($key in $srcKeys) {'+"^""`r`n"^""+' $dstKey = Join-Path $Dst $key.PSChildName'+"^""`r`n"^""+' Copy-Acl -Src $key.PSPath -Dst $dstKey'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $acl = Get-Acl -Path $Src -ErrorAction Stop'+"^""`r`n"^""+' $sections = [System.Security.AccessControl.AccessControlSections]::All -band (-bnot [System.Security.AccessControl.AccessControlSections]::Owner)'+"^""`r`n"^""+' $sddl = $acl.GetSecurityDescriptorSddlForm($sections)'+"^""`r`n"^""+' $acl.SetSecurityDescriptorSddlForm($sddl, $sections)'+"^""`r`n"^""+' Set-Acl -Path $Dst -AclObject $acl -ErrorAction Stop'+"^""`r`n"^""+'}'+"^""`r`n"^""+'function Rename-KeyWithAcl($Old, $New) {'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Copy-Item -LiteralPath $Old -Destination $New -Recurse -Force -ErrorAction Stop'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' throw "^""Failed to copy: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Copy-Acl -Src $Old -Dst $New'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to copy ACL: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Remove-Item -LiteralPath $Old -Force -Recurse -ErrorAction Stop | Out-Null'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Remove-Item -LiteralPath $New -Force -Recurse -ErrorAction Stop | Out-Null'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to clean up: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' throw "^""Failed to remove: $_"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'+"^""`r`n"^""+'$rawPath=''HKLM\Software\Classes\CLSID\{FEEE9C23-C4E2-4A34-8C73-FE8F9786C8B4}'''+"^""`r`n"^""+'$suffix =''.OLD'''+"^""`r`n"^""+'$global:fail = 0'+"^""`r`n"^""+'$global:ok = 0'+"^""`r`n"^""+'function Get-Real($s) {'+"^""`r`n"^""+' while ($s.EndsWith($suffix)) {'+"^""`r`n"^""+' $s = $s.Substring(0, $s.Length - $suffix.Length)'+"^""`r`n"^""+' }'+"^""`r`n"^""+' return $s'+"^""`r`n"^""+'}'+"^""`r`n"^""+'function Restore-KeyTree($Path) {'+"^""`r`n"^""+' $dest = Get-Real $Path'+"^""`r`n"^""+' $src = $Path'+"^""`r`n"^""+' Write-Host "^""Restoring key: ''$dest'' from ''$src''"^""'+"^""`r`n"^""+' if (-Not $src.EndsWith($suffix)) {'+"^""`r`n"^""+' $src += $suffix'+"^""`r`n"^""+' if (-Not (Test-Path -LiteralPath $src)) {'+"^""`r`n"^""+' Write-Host ''Skipping: No data.'''+"^""`r`n"^""+' Restore-Children $dest'+"^""`r`n"^""+' return'+"^""`r`n"^""+' }'+"^""`r`n"^""+' }'+"^""`r`n"^""+' if (Test-Path -LiteralPath $dest) {'+"^""`r`n"^""+' Write-Host ''Skipping to avoid data loss. Key already exists.'''+"^""`r`n"^""+' Write-Warning "^""Manual intervention may be required to fully restore from ''$src''."^""'+"^""`r`n"^""+' } else {'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Rename-KeyWithAcl -Old $src -New $dest -ErrorAction Stop'+"^""`r`n"^""+' Write-Host ''Successfully restored.'''+"^""`r`n"^""+' $global:ok++'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed: $_"^""'+"^""`r`n"^""+' $global:fail++'+"^""`r`n"^""+' }'+"^""`r`n"^""+' }'+"^""`r`n"^""+' Restore-Children $dest'+"^""`r`n"^""+'}'+"^""`r`n"^""+'function Restore-Children($Path) {'+"^""`r`n"^""+' Write-Host "^""Restoring values in ''$Path''"^""'+"^""`r`n"^""+' if (-Not (Test-Path -LiteralPath $Path)) {'+"^""`r`n"^""+' Write-Host ''Skipping: Key does not exist. No action needed.'''+"^""`r`n"^""+' return'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $values = ( `'+"^""`r`n"^""+' Get-Item -LiteralPath $Path -ErrorAction Stop | Select-Object -ExpandProperty Property `'+"^""`r`n"^""+' )'+"^""`r`n"^""+' foreach ($value in $values) {'+"^""`r`n"^""+' Write-Host "^""Restoring value ''$value''"^""'+"^""`r`n"^""+' if (-Not $value.EndsWith($suffix)) {'+"^""`r`n"^""+' Write-Host ''Skipping: No action needed.'''+"^""`r`n"^""+' continue'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $real = Get-Real $value'+"^""`r`n"^""+' Write-Host "^""Renaming to ''$real''."^""'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Rename-ItemProperty -LiteralPath $Path -Name $value -NewName $real -ErrorAction Stop'+"^""`r`n"^""+' Write-Host ''Successfully restored.'''+"^""`r`n"^""+' $global:ok++'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed: $_"^""'+"^""`r`n"^""+' $global:fail++'+"^""`r`n"^""+' }'+"^""`r`n"^""+' }'+"^""`r`n"^""+' $keys = @(Get-ChildItem -LiteralPath $Path -ErrorAction SilentlyContinue)'+"^""`r`n"^""+' foreach ($key in $keys) {'+"^""`r`n"^""+' Restore-KeyTree $key.PSPath'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'+"^""`r`n"^""+'Write-Host "^""Restoring registry key ''$rawPath'' recursively."^""'+"^""`r`n"^""+'$hive = $rawPath.Split(''\'')[0]'+"^""`r`n"^""+'$path = $hive + '':'' + $rawPath.Substring($hive.Length)'+"^""`r`n"^""+'Restore-KeyTree $path'+"^""`r`n"^""+'if ($global:fail) {'+"^""`r`n"^""+' Write-Error ''Failed to restore'''+"^""`r`n"^""+' Exit 1'+"^""`r`n"^""+'}'; Invoke-AsTrustedInstaller $cmd"
:: Restore files matching pattern: "%PROGRAMFILES%\Windows Defender Advanced Threat Protection\WATPCSP.dll" with additional permissions
PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%PROGRAMFILES%\Windows Defender Advanced Threat Protection\WATPCSP.dll.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 = @(); 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 process $($failedCount) items."^""; }; [Privileges]::RemovePrivilege('SeRestorePrivilege') | Out-Null; [Privileges]::RemovePrivilege('SeTakeOwnershipPrivilege') | Out-Null"

Support

This website relies on your support.

Support now

Your donation helps keep the project alive and improves its content ❤️.

Share this page: