Skip to content

Add-DefenderExclusionRemote

Windows: Adds exclusions to Windows Defender Antivirus

#Requires -Version 5.1
#Requires -Modules Defender

[CmdletBinding()]
Param (
    [string[]]$ExclusionPath,

    [string[]]$ExclusionExtension,

    [string[]]$ExclusionProcess,

    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process {
    try {
        $session = $null
        $prefParams = @{
            'ErrorAction' = 'Stop'
        }
        if ($ExclusionPath) { $prefParams.Add('ExclusionPath', $ExclusionPath) }
        if ($ExclusionExtension) { $prefParams.Add('ExclusionExtension', $ExclusionExtension) }
        if ($ExclusionProcess) { $prefParams.Add('ExclusionProcess', $ExclusionProcess) }

        if ($ComputerName -ne $env:COMPUTERNAME) {
            $sessionParams = @{
                'ComputerName' = $ComputerName
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential) {
                $sessionParams.Add('Credential', $Credential)
            }
            $session = New-CimSession @sessionParams
            $prefParams.Add('CimSession', $session)
        }

        if ($prefParams.Count -gt 1) {
            Add-MpPreference @prefParams
        }

        $prefs = if ($session) { Get-MpPreference -CimSession $session } else { Get-MpPreference }

        $result = [PSCustomObject]@{
            ExclusionPath      = $prefs.ExclusionPath
            ExclusionExtension = $prefs.ExclusionExtension
            ExclusionProcess   = $prefs.ExclusionProcess
            ComputerName       = $ComputerName
            Action             = "ExclusionsAdded"
            Status             = "Success"
        }

        Write-Output $result
    }
    catch {
        throw
    }
    finally {
        if ($null -ne $session) {
            Remove-CimSession $session
        }
    }
}

Specifies an array of file or folder paths to exclude from scanning.

Specifies an array of file extensions to exclude from scanning (e.g., ".txt", ".log").

Specifies an array of process names (e.g., "app.exe") to exclude from scanning.

Specifies the name of the target computer. Defaults to the local computer.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.