Public/Remove-specFromHost.ps1

function Remove-specFromHost {
    <#
    .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-specFromHosts -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-specFromHosts
    This will remove both "example1.com" and "example2.com" from the hosts file.
 
    .NOTES
    Version 1.0.0 - Initial release
    Author: owen.heaume
 
    #>


    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(
            Mandatory = $true,
            Position = 0,
            ValueFromPipelineByPropertyName = $true
        )]
        [string]$Hostname
    )

    begin {
        # Define the hosts file path once in the Begin block
        $hostsFilePath = "$($Env:WinDir)\system32\Drivers\etc\hosts"
        $hostsFile = Get-Content $hostsFilePath
    }

    process {
        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 -notmatch ".*\s+$escapedHostname.*" | Out-File $hostsFilePath -Encoding ASCII
                Write-Host ' done'
            }
        } else {
            Write-Host "$Hostname - not in hosts file (perhaps already removed); nothing to do" -ForegroundColor DarkYellow
        }
    }

    end {
        Write-Host 'Pipeline processing complete.'
    }
}