We seen how to delete a single entry from the hosts file – this is how we clear all entries
function clear-hostfilecontent { [CmdletBinding()] 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") $data 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.