# SophosEndpointUninstall.ps1
# Script for removal of Sophos Endpoint Security and Control and Activating Windows Defender
# collected and written by Thomas Erichsen following this article: https://support.sophos.com/support/s/article/KB-000033686?language=en_US
#
# No brain included, use your own

$DEBUG = $true
$ProgramList = "Sophos Remote Management System","Sophos Network Threat Protection","Sophos Client Firewall","Sophos Anti-Virus","Sophos AutoUpdate","Sophos Diagnostic Utility","Sophos Exploit Prevention","Sophos Clean","Sophos Patch Agent","Sophos Endpoint Defense"

Write-Host "Stopping Sophos AutoUpdate Service"
if (! $DEBUG) {net stop "Sophos AutoUpdate Service"}

foreach ($Program in $ProgramList)
{
  Write-Host "Searching for $Program"
  #First, we check in 64bit hive of the registry
  $entries = reg QUERY HKLM\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall /s /f $Program | findstr /R "\{.*}"
  
  #If necessary, we check the 32bit hive, too
  if ( $entries.length -eq 0 ) {
	  $entries = reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall /s /f $Program | findstr /R "\{.*}"
  }
  
  #extracting the classname
  $classname = $entries  | %{[System.Text.RegularExpressions.Regex]::Match($_, '\{.*}').Value}

  if ( $classname.length -gt 2 ) {
	  Write-Host "...Found" $classname
	  Write-Host "...Uninstalling $Program by command MsiExec.exe /X$classname /qn REBOOT=SUPPRESS"
	  if (! $DEBUG) {Start-Process MsiExec.exe "/X$classname /qn REBOOT=SUPPRESS" -wait -NoNewWindow}
    } elseif (($Program -eq "Sophos Anti-Virus") -and ($entries.length -gt 0)) {
	  #Hack 1, since the search pattern "Sophos Anti-Virus" appears also for the Update service and thus two registry keys are returned...
	  $classname = $classname[1]
	  Write-Host "...Uninstalling $Program by command MsiExec.exe /X$classname /qn REBOOT=SUPPRESS"
	  if (! $DEBUG) {Start-Process MsiExec.exe "/X$classname /qn REBOOT=SUPPRESS" -wait -NoNewWindow}	  
  } elseif (($Program -eq "Sophos Endpoint Defense") -and ($entries.length -gt 0)) {
	    #Hack 2, Sophos Endpoint Defense cannot be uninstalled with msiexec. Would be better to extract the UninstallString value, but I spent already too much time on this ;)
        Write-Host "...Uninstalling Sophos Endpoint Defense by command C:\Program Files\Sophos\Endpoint Defense\SEDuninstall.exe"
        if (! $DEBUG) {Start-Process "C:\Program Files\Sophos\Endpoint Defense\SEDuninstall.exe" -wait -NoNewWindow}
  } else {
	  Write-Host "...No entry found"
  }
}

Write-Host "Enabling Windows Defender"

if (! $DEBUG) {
	Set-MpPreference -DisableRealtimeMonitoring $false
	Set-MpPreference -DisableIOAVProtection $false
	Set-MpPreference -DisableBehaviorMonitoring $false
	Set-MpPreference -DisableOnAccessProtection $false
	start-service WinDefend
	start-service WdNisSvc
}

if ( $DEBUG ) {read-host "Press ENTER to close..."}