header image

Clearing hosts file

Posted by: | October 30, 2011 | No Comment |

We seen how to delete a single entry from the hosts file – this is how we clear all entries

function clear-hostfilecontent {            
 param ()            
 $file = Join-Path -Path $($env:windir) -ChildPath "system32\drivers\etc\hosts"            
 if (-not (Test-Path -Path $file)){            
   Throw "Hosts file not found"            
 Write-Verbose "Remove IP Addresses"            
 $data = ((Get-Content -Path $file) -notmatch "^\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")             
 Set-Content -Value $data -Path $file -Force -Encoding ASCII             


Don’t bother with parameters and change the regex to pick off any lines that don’t start with an IP address (or at least the pattern that represents an IP address).  Write the data back to the file.  I’ve used ASCII encoding on these because the default is Unicode which uses 2 bytes per character and isn’t really usable.

under: Networking, PowerShellV2