Public/Remove-specFromHostsFile.ps1
function Remove-specFromHostsFile { <# .SYNOPSIS Removes a specified hostname entry from the system's hosts file. .DESCRIPTION This function removes all occurrences of a specified hostname from the hosts file. It can remove both IPv4 and IPv6 entries associated with the given hostname. .PARAMETER Hostname The hostname (or domain name) you want to remove from the hosts file. The function will remove all entries matching this hostname, irrespective of the associated IP addresses. .INPUTS Accepts pipeline input for objects with a `Hostname` property. .OUTPUTS None .EXAMPLE Remove-specFromHostsFile -Hostname "example.com" This command will remove all entries of "example.com" from the hosts file. .EXAMPLE $hostEntries = @( [pscustomobject]@{ Hostname = "example1.com" }, [pscustomobject]@{ Hostname = "example2.com" } ) $hostEntries | Remove-specFromHostsFile This will remove both "example1.com" and "example2.com" from the hosts file. .NOTES Author: owen.heaume Version 1.0.0 - Initial release 1.0.1 - Slight refactor to better support unit testing (Create HostFilePath parameter) 1.0.2 - Improved error handling #> [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter( Mandatory = $true, Position = 0, ValueFromPipelineByPropertyName = $true )] [string]$Hostname, [string]$HostsFilePath = "$($Env:WinDir)\system32\Drivers\etc\hosts" ) begin { # Define the hosts file content try { $hostsFile = if (Test-Path $HostsFilePath -ea stop) { Get-Content $HostsFilePath -ea stop } else { @() } } catch { Write-Error "An error occurred reading the hosts file: $_" } } process { try { Write-Host "About to remove $Hostname from hosts file" -ForegroundColor Gray # Escape the hostname to handle special characters in regex $escapedHostname = [Regex]::Escape($Hostname) # Check if the hostname exists in the file if ($hostsFile -match ".*\s+$escapedHostname.*") { if ($PSCmdlet.ShouldProcess($Hostname, 'Remove from hosts file')) { Write-Host "$Hostname - removing from hosts file..." -ForegroundColor Yellow -NoNewline # Remove all entries matching the hostname $hostsFile = $hostsFile -notmatch ".*\s+$escapedHostname.*" $hostsFile | Out-File $HostsFilePath -Encoding ASCII -ea stop Write-Host 'done' } } else { Write-Host "$Hostname - not in hosts file; nothing to do" -ForegroundColor DarkYellow } } catch { Write-Error "An error occurred processing '$hostname': $_" } } end { Write-Host 'Processing complete.' } } |