Author: Shaun Hardneck – ThatLazyAdmin | Microsoft Defender
This PowerShell script allows users to enable, disable, or exclude individual Azure VMs from Defender for Servers using Microsoft Defender for Cloud APIs.
Previously, Defender for Servers could only be enabled at the subscription level, but Microsoft now supports per-VM management using API calls.
✔ Enable Defender for Servers Plan 1 (P1) on a single VM
✔ Disable Defender for Servers on a specific VM
✔ Exclude a VM from Defender for Servers while it's enabled at the subscription level
✔ Automatic installation of required PowerShell modules
✔ Token-based authentication using Azure REST APIs
✔ User-friendly prompts and color-coded output
Before running the script, ensure that:
-
You have PowerShell 7+ installed.
-
You have the Az PowerShell module installed (
Az.Accounts). -
You connect to Azure by running:
az login
If the Az module isn’t installed, run:
Install-Module -Name Az -AllowClobber -Scope CurrentUser -Force ./DefenderForServers.ps1It will prompt you for: - Subscription ID - Resource Group Name - Virtual Machine Name - Action to perform (Enable, Disable, or Exclude)
- Enable-P1 → Enable Defender for Servers Plan 1 for a VM - Disable → Remove Defender for Servers from a VM - Exclude → Exclude the VM from Defender for Servers (if enabled at the subscription level)
Following screenshot we can see Defender enabled on the server
Disable Defender on a Server
Defender showing as "Off"
Enter your Azure Subscription ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Enter the Resource Group Name: RG-Security
Enter the Virtual Machine Name: VM-Prod-01
Enter 'Enable-P1' to enable Defender for Servers P1, 'Disable' to remove Defender protection, or 'Exclude' to exclude this VM if Defender is set at the subscription level: Enable-P1
✅ Successfully updated Defender for Servers configuration for VM 'VM-Prod-01' Enter 'Enable-P1' to enable Defender for Servers P1, 'Disable' to remove Defender protection, or 'Exclude' to exclude this VM if Defender is set at the subscription level: Disable
✅ Successfully removed Defender for Servers from VM 'VM-Prod-01' Enter 'Enable-P1' to enable Defender for Servers P1, 'Disable' to remove Defender protection, or 'Exclude' to exclude this VM if Defender is set at the subscription level: Exclude
✅ Successfully excluded VM 'VM-Prod-01' from Defender for Servers.This project is licensed under the MIT License.
From the following Microsoft document you can learn more about the differnet options available to enable Microsoft Defender for Server. Read More
👤 Shaun Hardneck
📧 Email: Shaun@thatlazyadmin.com
🌍 Blog: ThatLazyAdmin
🔗 Feel free to reach out for support! 🚀



