A customer of mine wanted to offboard their servers from Microsoft Defender for Endpoint, I wrote a quick offboarding script. This is the same customer where I configured passive mode (link) first but we figured out that it would cost to much to run it in passive mode. It’s around 5 dollar per server per month, just to run it in passive mode. That was too much. So, we decided to offboard the servers again.
The script that I am about to show you can offboard multiple servers. I used an organisational unit in Active Directory as my source. You can use it any way you want off course.
I am utilising the Microsoft Defender for Endpoint Offboarding script but I use PowerShell to distribute and run it on all the destination servers.
Firstly, go to the Microsoft Security portal and go to:
Settings > Endpoints > Device Management > Offboarding:

After that, download the local script option:
(Select the correct operating system)

Save this script on the server where you are going to run the script. This the location for the variable: $Offboardingscript. Make sure this location matches.
In addition, you must be able to use a remote PowerShell session to the destination servers.
This is the script, and this is what it does:
- Get computer objects from Active Directory based on your query
- Gather the Microsoft Defender for Endpoint offboarding script
- Run each of these actions on each server:
- Create temp folders on the destination server
- Copy the Microsoft Defender for Endpoint offboarding script to the destination server
- Run the Microsoft Defender for Endpoint offboarding script on the destination server
- Remove the temp folder
$Servers = Get-ADComputer -filter * -SearchBase "YOUR OU" #Or what ever filter you want to use
$Offboardingscript = Get-Content -Path "C:\Temp\DefenderOffboarding\Offboardingscript.cmd"
foreach ($Server in $Servers.Name) {
Write-Output "Starting script for $Server"`
Invoke-Command -ComputerName $Server -ScriptBlock {
If (-not (Test-Path C:\Temp)) {
New-Item -Path C:\Temp -ItemType Directory
}
If (-not (Test-Path C:\Temp\DefenderOffboarding)) {
New-Item -Path C:\Temp\DefenderOffboarding -ItemType Directory
}
$using:OffboardingScript | Out-File C:\Temp\DefenderOffboarding\Offboardingscript.cmd -Encoding UTF8
}
Write-Output "Trying to Offboard machine from Defender for Endpoint"
Invoke-Command -ComputerName $Server -ScriptBlock {
try {
Start-Process -FilePath "C:\temp\defenderoffboarding\Offboardingscript.cmd" -Wait
Write-Output "DefenderOffboarding Completed succesfully"
}
catch {
Write-Error 'Defender offboarding failed'
}
}
Invoke-Command -ComputerName $Server -ScriptBlock {
Remove-Item -Path C:\Temp\DefenderOffboarding -Recurse -Force
}
}
Lastly, you can check whether the defender service stopped running with this command:
Get-Service -Name Sense

You can also embed this in the script.