Skip to content

Instantly share code, notes, and snippets.

@nichollsc81
Last active May 20, 2021 13:24
Show Gist options
  • Select an option

  • Save nichollsc81/2b2de1b8db95c92d3a060596bd88deb1 to your computer and use it in GitHub Desktop.

Select an option

Save nichollsc81/2b2de1b8db95c92d3a060596bd88deb1 to your computer and use it in GitHub Desktop.
Removes record from host file
# credit Tom Chantler: https://github.com/TomChantler/EditHosts
function Remove-RecordFromHosts
{
[cmdletbinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Hostname
)
begin
{
$ErrorActionPreference = 'Stop'
if (! ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "Function requires elevation."
Break
}
$hostsFilePath = "$($env:WinDir)\system32\Drivers\etc\hosts"
$hostsFile = Get-Content $hostsFilePath
Write-Verbose "About to remove $Hostname from hosts file"
}
process
{
$escapedHostname = [Regex]::Escape($Hostname)
if (($hostsFile) -match ".*\s+$escapedHostname.*")
{
Write-Verbose "$Hostname - removing from hosts file... "
$hostsFile -notmatch ".*\s+$escapedHostname.*" | Out-File $hostsFilePath
Write-Host "Done."
}
else
{
Write-Host "$Hostname - not in hosts file (perhaps already removed); nothing to do"
}
}
}
#Remove-RecordFromHosts www.google.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment