Clearing a DNS server cache using VBscript and WMI

Archive for August, 2004

Clearing a DNS server cache using VBscript and WMI

Posted by

When troubleshooting a DNS server on Windows Server 2003, you may need to clear the DNS cache. This can be done from the GUI: dnsmgmt.msc, right-click the server, Clear Cache. Whacking the DNS cache can also be done from the command line: dnscmd %computername% /clearcache. Then again, you may want to clear remotely using a script (or clear a number of servers at once).

The VBScript below will clear out the cache. It uses WMI to connect to the MicrosoftDNS namespace. If that namespace does not exist, as it will not on servers that do not have DNS installed, the WMI will throw a 0x8004100E error (Invalid namespace). So the script first loops thru the available namespaces to confirm that MicrosoftDNS is present. If it is, the script connects, and executes the.ClearCache()method.



‘ Name:   dnscachecls.vbs

‘ Author: J Wolfgang Goerlich
‘ Date:   2004-08/03

‘ Description: Clear DNS cache using WMI


Option Explicit

‘ Dimension variables

Dim wmi ‘ SWbemServices, WMI interface
Dim wns ‘ WMI namespace
Dim wql ‘ WMI Query Language
Dim computer
Dim oShell
Dim results
Dim namespace
Dim dns
Dim isdnsserver

‘ Get the computer name

Set oShell = WScript.CreateObject(“WScript.Shell”)
if WScript.Arguments.UnNamed.Count >= 1 then
computer = Trim(LCase(WScript.Arguments(0)))
computer = LCase(oShell.ExpandEnvironmentStrings(“%ComputerName%”))
end if

‘ Confirm the server is a DNS server

wns = “winmgmts:\\” & computer & “\root”
isdnsserver = false

set results = GetObject(wns).InstancesOf(“__NAMESPACE”)

For Each namespace in results
if namespace.Name = “MicrosoftDNS” then isdnsserver = true

if isdnsserver = false then
Wscript.Echo computer & ” is not a DNS server.”
end if

‘ Clear the DNS cache

wns = “winmgmts:\\” & computer & “\root\MicrosoftDNS”
wql = “Select * From MicrosoftDNS_Cache”

Set wmi = GetObject(wns)
Set results = wmi.ExecQuery(wql)

For Each dns in results

Wscript.Echo “DNS cache cleared on ” & computer