Quickly Add and Remove Entries in Hosts File with PowerShell
Sometimes you still need to modify the old hosts file. Do it faster with a PowerShell script!
Modify-Hosts.ps1 is a menu driven CLI interface that looks like this:
Current hosts entries:
1.1.1.1 host1
2.2.2.2 host2
[1.] Add to hosts
[2.] Remove from hosts
[3.] Clear hosts
[4.] Exit
Choose:
Modify-Hosts.ps1
#Requires -RunAsAdministrator
#
# Author: HullB
# Date Created: 10-21-2022
# Date Modified: NA
# Title: Modify-Hosts
# Purpose: A script to add or remove entries from the hosts file on a local PC.
# Notes: Duplicate lines will be automatically removed. If hostname and ip address
# are used as paramters 1 and 2, they will be added to hosts.
Remove-Variable Hostname -ErrorAction Ignore
Remove-Variable IPAddress -ErrorAction Ignore
$Hostname = $args[0]
$IPAddress = $args[1]
$hostfilePath = "$env:SystemRoot\System32\Drivers\etc\hosts"
$hostfileBkupPath = "$env:SystemRoot\System32\Drivers\etc\hosts.orig"
#Make a backup copy of hosts if one does not already exists
if (-not(Test-Path -Path $hostfileBkupPath)) {
Copy-Item $hostfilePath -Destination $hostfileBkupPath
}
#Get user input
function Print-Options() {
Write-Host "`n[1.] Add to hosts `n[2.] Remove from hosts`n[3.] Clear hosts`n[4.] Exit"
$opt = Read-Host "`n`nChoose"
if([string]::IsNullOrEmpty($opt)) {
Write-Warning "Invalid choice selected. Exiting."
}
else{
return $opt
}
}
#Add a line to hosts if script was issued with paramters
if ($Hostname -and $IPAddress) {
$newHost = $IPAddress + " " + $Hostname
Add-Content -Path $hostfilePath -Value $newHost
}
while($true){
#Sort and remove duplicates
$hostsfileContent = Get-Content $hostfilePath | Where { $_ -notmatch "#" } | sort | get-unique
Copy-Item $hostfileBkupPath -Destination $hostfilePath
Start-Sleep -Seconds 1
Add-Content -Path $hostfilePath -Value $hostsfileContent
#Display current content of hosts
Write-Host "`nCurrent hosts entries:"
$hostsfileContent = Get-Content $hostfilePath | Where { $_ -notmatch "#" }
$hostsfileContent
$opt = Print-Options
switch($opt){
1{#Add to hosts file
$Hostname = Read-Host -Prompt "Enter Hostname to add"
$IPAddress = Read-Host -Prompt "Enter IP Address for $Hostname"
$newHost = $IPAddress + " " + $Hostname
Add-Content -Path $hostfilePath -Value $newHost
}
2{#Remove from hosts file
$RemoveItem = Read-Host -Prompt "Enter Hostname or IP Address of line to remove"
Set-Content -Path $hostfilePath -Value (get-content -Path $hostfilePath | Select-String -Pattern $RemoveItem -NotMatch)
}
3{#Restore Original
Copy-Item $hostfileBkupPath -Destination $hostfilePath
}
4{Exit}
Default{"Invalid choice selected. Restarting loop."}
}
}