All scripts
Automation 332

Clear-DnsCache (Proactive Remediation)

An Intune Proactive Remediation pair that detects a bloated or stale DNS resolver cache and clears it, a common cause of intermittent name resolution complaints that a simple restart usually fixes anyway.

Clear-DnsCache.ps1
<#
.SYNOPSIS
    Intune Proactive Remediation pair: detect and clear a stale DNS cache.

.DESCRIPTION
    Two script blocks in one file, separated below. The detection script
    checks the number of cached DNS entries and flags the device if it
    exceeds a threshold, a common precursor to the intermittent name
    resolution complaints that a cache clear usually fixes. The
    remediation script clears the cache. Deploy the detection block as
    the detection script and the remediation block as the remediation
    script in an Intune Proactive Remediation.

.NOTES
    Split this file into two separate .ps1 files when uploading to
    Intune: one for detection, one for remediation.

.AUTHOR
    Shehryar Hassan
#>

# ============================================================
# Detection script (Detect-StaleDnsCache.ps1)
# ============================================================
$cacheEntries = (Get-DnsClientCache -ErrorAction SilentlyContinue | Measure-Object).Count
$threshold = 500

if ($cacheEntries -gt $threshold) {
    Write-Output "DNS cache has $cacheEntries entries, exceeds threshold of $threshold."
    exit 1
}

Write-Output "DNS cache has $cacheEntries entries, within normal range."
exit 0

# ============================================================
# Remediation script (Remediate-StaleDnsCache.ps1)
# ============================================================
# Clear-DnsClientCache
# Write-Output "DNS client cache cleared."
# exit 0

Read it before you run it, and test in a safe tenant first.