Private/Hosts/Remove-HostsEntry.ps1
<# .SYNOPSIS Removes an entry from the HOSTS file. .PARAMETER Hostname The hostname to create. .PARAMETER Hosts The path to the hosts file. #> Function Remove-HostsEntry { [CmdletBinding(SupportsShouldProcess = $true)] Param( [Parameter(Position = 1, Mandatory = $true, HelpMessage = "Hostname entry")] [ValidateNotNullOrEmpty()] [string]$Hostname , [Parameter(Position = 3)] [ValidateScript({ Test-Path $_ -PathType "Leaf" })] [string]$Hosts = (Join-Path $env:windir -ChildPath "System32\drivers\etc\hosts") ) Begin { $escapedHostname = [regex]::Escape($Hostname) } Process { $existing = Get-HostsEntry $Hostname -Hosts $Hosts If ($existing -and $PSCmdlet.ShouldProcess($Hosts, "Remove $($Hostname)")) { $contents = Get-Content $Hosts $contents | Where-Object { $_ -notmatch "\s$($escapedHostname)(?:\s|$)" } | Set-Content $Hosts } } } |