#===========================================================
#
# HOSTS 3.1, 2026-07-13
#
# Author:   IPWorX.com
# Purpose:  The HOSTS project creates DNS black holes on local
#           machines. This script merges NewHOST file entries
#           with the local HOSTS file. 
#    
#           This script is called from client PCs manually or
#           via a domain GPO. This script should not be edited
#           outside of the CONFIGURATION section.
#
# This script and more to help manage your network found, 
# managed and happily shared with documentation on usage at
# the Information Processing Work eXchange.
#                   https://www.IPWORX.com
#
#===========================================================

#===================== CONFIGURATION =======================

$NewHOSTFile = "\\SERVER1\PUBLIC\NewHOST.txt"

#===================== CONFIGURATION =======================

$ClientHOSTFile = "$env:SystemRoot\system32\drivers\etc\hosts"

if (-not (Test-Path $NewHOSTFile)) {
    Write-Warning "Cannot find $NewHOSTFile. Aborting MergeHOSTS."
    exit
}

if (Test-Path $ClientHOSTFile) {
    $FileContent = Get-Content -Path $ClientHOSTFile -Raw
} else {
    Write-Warning "Cannot find local HOST file. Aborting MergeHOSTS."
    exit
}

$FileContent = $FileContent -replace "(?s)#BEGIN-IPWORX-HOSTS.*?#END-IPWORX-HOSTS", ""
$FileContent = $FileContent -replace "(\r\n){2,}", "`r`n"

$IPWorXHOSTSContent = Get-Content -Path $NewHOSTFile -Raw
$FinalContent = $FileContent.Trim() + "`r`n" + $IPWorXHOSTSContent

$FinalContent | Out-File -FilePath $ClientHOSTFile -Encoding ASCII -Force