J Wolfgang Goerlich's thoughts on Information Security
Clearing a DNS server cache using VBscript and WMI

By wolfgang. 3 August 2004 10:31

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)))
else
    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
Next

if isdnsserver = false then
    Wscript.Echo computer & " is not a DNS server."
    Wscript.Quit
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
    dns.ClearCache()
Next

Wscript.Echo "DNS cache cleared on " & computer

Tags:

Systems Engineering | Troubleshooting

    Log in