summaryrefslogtreecommitdiff
path: root/ansible/scripts/setup-defender-gpo.ps1
blob: 688949aa1e7bbf54ffbbaf3fa96a39fe13633ed7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
param (
    [string]$DomainName = "contoso.com"
)

$scriptName = $MyInvocation.MyCommand.Name
$logFile = "C:\Logs\${scriptName}_log.txt"
Start-Transcript -Path $logFile -Append

Import-Module GroupPolicy -ErrorAction Stop

$DomainNameDN = "DC=$($DomainName.Split(".")[0]),DC=$($DomainName.Split(".")[1])"
$DomainUsers = Get-ADGroup "Domain Users" -ErrorAction Stop

$GpoName = "DisableMicrosoftDefender"

try {
    $GPO = New-GPO -Name $GpoName -Comment "GPO to disable Microsoft Defender in test environment" -ErrorAction Stop
    Write-Host "[INFO] Created GPO '$GpoName'"

    Set-GPPermission -Name $GPO.DisplayName -PermissionLevel GpoEditDeleteModifySecurity -TargetName $DomainUsers.Name -TargetType Group -ErrorAction Stop
    Write-Host "[INFO] Set GpoEditDeleteModifySecurity permissions for '$($DomainUsers.Name)' on GPO '$GpoName'"

    $RegistrySettings = @(
        @{
            Key = "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender"
            ValueName = "DisableAntiSpyware"
            Value = 1
            Type = "DWORD"
        },
        @{
            Key = "HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection"
            ValueName = "DisableRealtimeMonitoring"
            Value = 1
            Type = "DWORD"
        }
    )

    foreach ($Setting in $RegistrySettings) {
        Set-GPRegistryValue -Name $GpoName -Key $Setting.Key -ValueName $Setting.ValueName -Type $Setting.Type -Value $Setting.Value -ErrorAction Stop
        Write-Host "[INFO] Set registry value: $($Setting.Key)\$($Setting.ValueName) = $($Setting.Value)"
    }

    New-GPLink -Name $GPO.DisplayName -Target "$DomainNameDN" -LinkEnabled Yes -ErrorAction Stop
    Write-Host "[INFO] Created GP link for '$GpoName' on $DomainNameDN"
}
catch {
    Write-Host "[ERR] Failed to configure GPO '$GpoName': $_"
}

Stop-Transcript