Skip to main content

Disable Defender Antivirus minifilter driver

Overview

About this script

This script improves your privacy on Windows.

These changes use Windows system commands to update your settings.

This script disables Defender's core monitoring component that tracks and controls your system activities.

This component has several names, including:

  • Windows Defender Mini-Filter Driver 1 2
  • Microsoft antimalware file system filter driver 3
  • Microsoft Defender Antivirus On-Access Malware Protection Mini-Filter Driver 3 4
  • Windows Defender Real-Time scanning filesystem filter driver 5
  • Windows Defender On-Access Malware Protection Mini-Filter Driver 2
  • Microsoft Defender Antivirus Mini-Filter Driver 4

This driver is a component of Defender Antivirus 6 7 8 and Defender for Endpoint 9. It runs at the deepest level of Windows and monitors your system activities 10.

The driver has these primary functions:

  • Monitors and restricts activities such as:
    • File system operations 10 11 12 13
    • Process creation and termination 10 11 12 13 14 15
    • Windows registry operations 11 12 13 16 17
    • System drivers and boot processes 15
    • Dev Drive (storage volumes used for development) 18
  • Collects and reports telemetry on system activity 11
  • Enables communication between Defender components 11 12 19 such as MsMpEng.exe 13 15 19
  • Provides security features such as:
    • Endpoint Detection and Response (EDR) capabilities 6, sending telemetry 20
    • Data Loss Prevention (DLP) 11 to prevent unauthorized data sharing
    • Tamper Protection to restrict system modifications 16
    • Host Intrusion Prevention System (HIPS) 14

This script enhances privacy by:

  • Stopping continuous system monitoring by Windows Defender
  • Blocking the collection of system activity data
  • Reducing telemetry sent to Microsoft
  • Limiting surveillance capabilities
  • Allowing deeper privacy configurations, including disabling Defender

This script may improve system performance by:

  • Reducing background activities
  • Using less system resources
  • Removing file system slowdowns

This script may increase system stability. This driver can sometimes cause system crashes (blue screen errors) 3 5 12. Disabling it may prevent these issues 1 21.

However, it may reduce your security by:

  • Impairing real-time malware protection
  • Removing protection against unauthorized system changes
  • Stopping monitoring of suspicious process activities
  • Disabling protection of sensitive system files
Caution

This action may leave your system more vulnerable to malware and unwanted changes.

Technical Details

The driver is installed by Windows-Defender-Drivers package 22.

This script:

  • Removes HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance!Altitude 16
    • This method worked on older versions of Defender Antivirus before April 2024 16
    • Tests show on modern Windows versions (Windows 10 Pro ≥ 22H2, Windows 11 Pro ≥ 21H2), the operation reports success but the value remains unchanged.
  • Disables the WdFilter driver service 2 3
  • Removes the driver file at %SYSTEMROOT%\System32\drivers\WdFilter.sys 2 3 4

Overview of default service statuses

OS VersionStatusStart type
Windows 10 (≥ 22H2)🟢 RunningBoot
Windows 11 (≥ 23H2)🟢 RunningBoot

This script uses Batch (batchfile) scripting language.

Not Advised

This script should only be used by advanced users. This script is not recommended for daily use as it breaks important functionality. Do not run it without having backups and system snapshots.

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 system modification restrictions category. This category disables features that restrict system modifications in Windows. This enables deeper system modifications, enhancing privacy by allowing the removal or disabling of data-collecting components like Defender. These features raise several concerns: Less user control: • Users can't... 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 Antivirus minifilter driver.
  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
:: Delete the registry value "Altitude" from the key "HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance" 
PowerShell -ExecutionPolicy Unrestricted -Command "$keyName = 'HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance'; $valueName = 'Altitude'; $hive = $keyName.Split('\')[0]; $path = "^""$($hive):$($keyName.Substring($hive.Length))"^""; Write-Host "^""Removing the registry value '$valueName' from '$path'."^""; if (-Not (Test-Path -LiteralPath $path)) { Write-Host 'Skipping, no action needed, registry key does not exist.'; Exit 0; }; $existingValueNames = (Get-ItemProperty -LiteralPath $path).PSObject.Properties.Name; if (-Not ($existingValueNames -Contains $valueName)) { Write-Host 'Skipping, no action needed, registry value does not exist.'; Exit 0; }; try { if ($valueName -ieq '(default)') { Write-Host 'Removing the default value.'; $(Get-Item -LiteralPath $path).OpenSubKey('', $true).DeleteValue(''); } else { Remove-ItemProperty -LiteralPath $path -Name $valueName -Force -ErrorAction Stop; }; Write-Host 'Successfully removed the registry value.'; } catch { Write-Error "^""Failed to remove the registry value: $($_.Exception.Message)"^""; }"
:: Disable the service `WdFilter` using TrustedInstaller privileges
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 = '$serviceQuery = ''WdFilter'''+"^""`r`n"^""+'$stopWithDependencies= $false'+"^""`r`n"^""+'<# -- 1. Skip if service does not exist #>'+"^""`r`n"^""+'$service = Get-Service -Name $serviceQuery -ErrorAction SilentlyContinue'+"^""`r`n"^""+'if(!$service) {'+"^""`r`n"^""+' Write-Host "^""Service query `"^""$serviceQuery`"^"" did not yield any results, no need to disable it."^""'+"^""`r`n"^""+' Exit 0'+"^""`r`n"^""+'}'+"^""`r`n"^""+'$serviceName = $service.Name'+"^""`r`n"^""+'Write-Host "^""Disabling service: `"^""$serviceName`"^""."^""'+"^""`r`n"^""+'<# -- 2. Stop if running #>'+"^""`r`n"^""+'if ($service.Status -eq [System.ServiceProcess.ServiceControllerStatus]::Running) {'+"^""`r`n"^""+' Write-Host "^""`"^""$serviceName`"^"" is running, attempting to stop it."^""'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Write-Host "^""Stopping the service `"^""$serviceName`"^""."^""'+"^""`r`n"^""+' $stopParams = @{ `'+"^""`r`n"^""+' Name = $ServiceName'+"^""`r`n"^""+' Force = $true'+"^""`r`n"^""+' ErrorAction = ''Stop'''+"^""`r`n"^""+' }'+"^""`r`n"^""+' if (-not $stopWithDependencies) {'+"^""`r`n"^""+' $stopParams[''NoWait''] = $true'+"^""`r`n"^""+' }'+"^""`r`n"^""+' Stop-Service @stopParams'+"^""`r`n"^""+' Write-Host "^""Stopped `"^""$serviceName`"^"" successfully."^""'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' if ($_.FullyQualifiedErrorId -eq ''CouldNotStopService,Microsoft.PowerShell.Commands.StopServiceCommand'') {'+"^""`r`n"^""+' Write-Warning "^""The service `"^""$serviceName`"^"" does not accept a stop command and may need to be stopped manually or on reboot."^""'+"^""`r`n"^""+' } else {'+"^""`r`n"^""+' Write-Warning "^""Failed to stop service `"^""$ServiceName`"^"". It will be stopped after reboot. Error: $($_.Exception.Message)"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' }'+"^""`r`n"^""+'} else {'+"^""`r`n"^""+' Write-Host "^""`"^""$serviceName`"^"" is not running, no need to stop."^""'+"^""`r`n"^""+'}'+"^""`r`n"^""+'<# -- 3. Skip if service info is not found in registry #>'+"^""`r`n"^""+'$registryKey = "^""HKLM:\SYSTEM\CurrentControlSet\Services\$serviceName"^""'+"^""`r`n"^""+'if (-Not (Test-Path $registryKey)) {'+"^""`r`n"^""+' Write-Host "^""`"^""$registryKey`"^"" is not found in registry, cannot enable it."^""'+"^""`r`n"^""+' Exit 0'+"^""`r`n"^""+'}'+"^""`r`n"^""+'<# -- 4. Skip if already disabled #>'+"^""`r`n"^""+'if( $(Get-ItemProperty -Path "^""$registryKey"^"").Start -eq 4) {'+"^""`r`n"^""+' Write-Host "^""`"^""$serviceName`"^"" is already disabled from start, no further action is needed."^""'+"^""`r`n"^""+' Exit 0'+"^""`r`n"^""+'}'+"^""`r`n"^""+'<# -- 5. Disable service #>'+"^""`r`n"^""+'try {'+"^""`r`n"^""+' Set-ItemProperty `'+"^""`r`n"^""+' -LiteralPath $registryKey `'+"^""`r`n"^""+' -Name "^""Start"^"" `'+"^""`r`n"^""+' -Value 4 `'+"^""`r`n"^""+' -ErrorAction Stop'+"^""`r`n"^""+' Write-Host ''Successfully disabled the service. It will not start automatically on next boot.'''+"^""`r`n"^""+'} catch {'+"^""`r`n"^""+' Write-Error "^""Failed to disable the service. Error: $($_.Exception.Message)"^""'+"^""`r`n"^""+' Exit 1'+"^""`r`n"^""+'}'; Invoke-AsTrustedInstaller $cmd"
:: Soft delete files matching pattern: "%SYSTEMROOT%\System32\drivers\WdFilter.sys" with additional permissions
PowerShell -ExecutionPolicy Unrestricted -Command "$pathGlobPattern = "^""%SYSTEMROOT%\System32\drivers\WdFilter.sys"^""; $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 the registry value "Altitude" in key "HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance" to its original value 
PowerShell -ExecutionPolicy Unrestricted -Command "$data = '328010'; $rawType = 'REG_SZ'; $rawPath = 'HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Instances\WdFilter Instance'; $value = 'Altitude'; $hive = $rawPath.Split('\')[0]; $path = "^""$($hive):$($rawPath.Substring($hive.Length))"^""; Write-Host "^""Restoring value '$value' at '$path' with type '$rawType' and value '$data'."^""; if (-Not $rawType) { throw "^""Internal privacy$([char]0x002E)sexy error: Data type is not provided for data '$data'."^""; }; if (-Not (Test-Path -LiteralPath $path)) { try { New-Item -Path $path -Force -ErrorAction Stop | Out-Null; Write-Host 'Successfully created registry key.'; } catch { throw "^""Failed to create registry key: $($_.Exception.Message)"^""; }; }; $currentData = Get-ItemProperty -LiteralPath $path -Name $value -ErrorAction SilentlyContinue | Select-Object -ExpandProperty $value; if ($currentData -eq $data) { Write-Host 'Skipping, no changes required, the registry data is already as expected.'; Exit 0; }; try { $type = switch ($rawType) { 'REG_SZ' { 'String' }; 'REG_DWORD' { 'DWord' }; 'REG_QWORD' { 'QWord' }; 'REG_EXPAND_SZ' { 'ExpandString' }; default { throw "^""Internal privacy$([char]0x002E)sexy error: Failed to find data type for: '$rawType'."^""; }; }; Set-ItemProperty -LiteralPath $path -Name $value -Value $data -Type $type -Force -ErrorAction Stop; Write-Host 'Successfully restored the registry value.'; } catch { throw "^""Failed to restore the value: $($_.Exception.Message)"^""; }"
:: Restore the service `WdFilter` using TrustedInstaller privileges
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 = '$serviceQuery = ''WdFilter'''+"^""`r`n"^""+'$defaultStartupMode = ''Boot'''+"^""`r`n"^""+'<# -- 1. Skip if service does not exist #>'+"^""`r`n"^""+'$service = Get-Service -Name $serviceQuery -ErrorAction SilentlyContinue'+"^""`r`n"^""+'if (!$service) {'+"^""`r`n"^""+' Write-Warning "^""Service query `"^""$serviceQuery`"^"" did not yield and results. Revert cannot proceed."^""'+"^""`r`n"^""+' Exit 1'+"^""`r`n"^""+'}'+"^""`r`n"^""+'$serviceName = $service.Name'+"^""`r`n"^""+'Write-Host "^""Restoring registry settings for service `"^""$serviceName`"^"" to default startup mode `"^""$defaultStartupMode`"^""."^""'+"^""`r`n"^""+'<# -- 2. Skip if service info is not found in registry #>'+"^""`r`n"^""+'$registryKey = "^""HKLM:\SYSTEM\CurrentControlSet\Services\$serviceName"^""'+"^""`r`n"^""+'if (-Not (Test-Path $registryKey)) {'+"^""`r`n"^""+' Write-Warning "^""`"^""$registryKey`"^"" is not found in registry. Revert cannot proceed."^""'+"^""`r`n"^""+' Exit 1'+"^""`r`n"^""+'}'+"^""`r`n"^""+'<# -- 3. Enable if not already enabled #>'+"^""`r`n"^""+'$defaultStartupRegValue = switch ($defaultStartupMode) {'+"^""`r`n"^""+' ''Boot'' { 0 }'+"^""`r`n"^""+' ''System'' { 1 }'+"^""`r`n"^""+' ''Automatic'' { 2 }'+"^""`r`n"^""+' ''Manual'' { 3 }'+"^""`r`n"^""+' ''Disabled'' { 4 }'+"^""`r`n"^""+' default {'+"^""`r`n"^""+' Write-Error "^""Error: Unknown startup mode specified: `"^""$defaultStartupMode`"^"". Revert cannot proceed."^""'+"^""`r`n"^""+' return'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'+"^""`r`n"^""+'if ($(Get-ItemProperty -Path "^""$registryKey"^"").Start -eq $defaultStartupRegValue) {'+"^""`r`n"^""+' Write-Host "^""`"^""$serviceName`"^"" is has already default startup mode: `"^""$defaultStartupMode`"^""."^""'+"^""`r`n"^""+'} else {'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Set-ItemProperty $registryKey -Name Start -Value $defaultStartupRegValue -Force'+"^""`r`n"^""+' Write-Host "^""Successfully restored `"^""$serviceName`"^"" with `"^""$defaultStartupMode`"^"" start, this may require restarting your computer."^""'+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Error "^""Could not enable `"^""$serviceName`"^"": $_"^""'+"^""`r`n"^""+' Exit 1'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'+"^""`r`n"^""+'<# -- 4. Start if not running (must be enabled first) #>'+"^""`r`n"^""+'if ($defaultStartupMode -eq ''Automatic'' -or $defaultStartupMode -eq ''Boot'' -or $defaultStartupMode -eq ''System'') {'+"^""`r`n"^""+' if ($service.Status -ne [System.ServiceProcess.ServiceControllerStatus]::Running) {'+"^""`r`n"^""+' Write-Host "^""`"^""$serviceName`"^"" is not running, trying to start it."^""'+"^""`r`n"^""+' try {'+"^""`r`n"^""+' Start-Service -Name $serviceName -ErrorAction Stop'+"^""`r`n"^""+' Write-Host ''Service started successfully.'''+"^""`r`n"^""+' } catch {'+"^""`r`n"^""+' Write-Warning "^""Failed to restart service. It will be started after reboot. Error: $($_.Exception.Message)"^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+' } else {'+"^""`r`n"^""+' Write-Host "^""`"^""$serviceName`"^"" is already running, no need to start."^""'+"^""`r`n"^""+' }'+"^""`r`n"^""+'}'; Invoke-AsTrustedInstaller $cmd"
:: Restore files matching pattern: "%SYSTEMROOT%\System32\drivers\WdFilter.sys" with additional permissions
PowerShell -ExecutionPolicy Unrestricted -Command "$revert = $true; $pathGlobPattern = "^""%SYSTEMROOT%\System32\drivers\WdFilter.sys.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: