PS-Tip #1 – Remote DNS Cache Clearing
This is part of the PS-Tips series: short posts introducing useful PowerShell snippets for system administration tasks.
Prerequisites
There are requirements to run remote PowerShell commands and I'll cover the details of setting the prerequisites in a later post. The process for getting setup isn't too difficult so if it doesn't work right away, make sure the following are setup on your systems:
- Windows PowerShell 2.0 or later1
- .NET Framework 3.0 or later
- Windows Remote Management 2.0 or later
The Solution
Today's PowerTip deals with remotely executing the ipconfig /flushdns
command on other systems.
The code is as follows:
$Computer = hostname #Replace hostname with the name of the system you want to execute the command on
Invoke-Command -script {Clear-DnsClientCache } -ComputerName $Computer
How It Works
The logic isn't too complicated and structure is like this:
- Create a variable
$Computer
with the name of the target (remote) system - Use the
Invoke-Command
cmdlet to run a script (-Script
) on a target computer (-ComputerName
) - The
{Clear-DnsClientCache}
command is actually just the 'Clear-DnsClientCache' command defined as block command (the space between the{}
is the block command)
The execution flow:
- A variable is defined
Invoke-Command
creates a script which executes theClear-DNSClientCache
command and then runs it on the target$Computer
Real-World Usage
I wrote this script after making some DNS changes and having users call in because the change hadn't propagated yet. Instead of walking through the process of getting them into a terminal and typing ipconfig /flushdns
I could just target their computer name and execute this. You can even create an array of computers and do a ForEach
loop on all of them and get everything changed at once!
Further Resources
Let me know if you like the script or want to expand it! Send me any questions or comments or topics you'd like to see covered and we'll explore more as time goes on. You can see more examples of cool PowerShell tricks at my GitHub here: IT-Infrastructure-Super-Utility
Thanks for reading!