PowerShell script to update hosts file

Posted by John Liu on Wednesday, July 17, 2024

You may need to add computer entery into hosts file for easy RDP access. Run following PowerShell script in administrator mode to add the target machine/IP into hosts file. Or you can manually open the C:\Windows\System32\drivers\etc\hosts file and edit it.

#Run this script in Administrator mode
cls
$Srv = Read-Host -Prompt "Target Server Name"
$IP = Read-Host -Prompt "Target Server IP"
$newEntry =$IP + "		" + $Srv
$hostfile = Get-Content C:\Windows\System32\drivers\etc\hosts
[bool]$Update = 0
if (-NOT ($IP | Select-String -Pattern "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+")) {
    Write-Output "IP address not valid!"
} elseif($hostfile | Select-String -Pattern "$IP\s+$Srv") {
    Write-Output "Server/IP entry already exists!"
} elseif ($hostfile | Select-String -Pattern "$IP\s+") {
    $oldSrv = $hostfile | Select-String -Pattern "$IP\s+"
    $oldSrv = $oldSrv -replace "$IP\s+",""
    $respond = Read-Host -Prompt "IP address already assigned to a different server ($oldSrv). Do you want to replace it?(Y/N)"
    if ($respond.ToUpper() -eq "Y") {
        $oldEntry = ($hostfile | Select-String -Pattern "$IP\s+")
        $hostfile = $hostfile -replace $oldEntry, $newEntry
        [bool]$Update = 1
        
    }
} elseif ($hostfile | Select-String -Pattern "\s+$Srv") {
    $oldSrv = $hostfile | Select-String -Pattern "\s+$Srv"
    $oldSrv = $oldSrv -replace "\s+$Srv",""
    $respond = Read-Host -Prompt "Server already assigned a different IP ($oldSrv). Do you want to replace it?(Y/N)"
    if ($respond.ToUpper() -eq "Y") {
        $oldEntry = ($hostfile | Select-String -Pattern "\s+$Srv")
        $hostfile = $hostfile -replace $oldEntry, $newEntry
        $hostfile
        [bool]$Update = 1
        
    }
} else {
    $hostfile = $hostfile + $newEntry
    [bool]$Update = 1
}

if ($Update) {
    #$hostfile |Out-File C:\Windows\System32\drivers\etc\hosts
    Write-output "File updated!"
} else {
    Write-Output "No change made!"
}