Skip to content

Instantly share code, notes, and snippets.

@bgallagh3r
Created December 10, 2014 00:43
Show Gist options
  • Save bgallagh3r/722ddc23ed452889970d to your computer and use it in GitHub Desktop.
Save bgallagh3r/722ddc23ed452889970d to your computer and use it in GitHub Desktop.
Powershell script to add/edit/list/remove entries from the hosts file.
Set-ExecutionPolicy RemoteSigned
# Edit HOSTS file Script
# Brian Gallagher (http://briangallagher.me)
#
# If you use Sublime text, and don't have an alias for it yet, uncomment the line below and change the path to ST
#Set-Alias st 'C:\Program Files\Sublime Text 3\sublime_text.exe'
$file = join-path -path $env:SystemRoot -childpath "System32\drivers\etc\hosts"
function add-host([string]$filename, [string]$ip, [string]$hostname) {
remove-host $filename $hostname
$ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename
}
function remove-host([string]$filename, [string]$hostname) {
$c = Get-Content $filename
$newLines = @()
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
if ($bits[1] -ne $hostname) {
$newLines += $line
}
} else {
$newLines += $line
}
}
# Write file
Clear-Content $filename
foreach ($line in $newLines) {
$line | Out-File -encoding ASCII -append $filename
}
}
function edit-hosts([string]$filename) {
#using an editor like sublime text
st $filename
#use the command below if you want to use another editor
#start $filename
}
function print-hosts([string]$filename) {
$c = Get-Content $filename
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
Write-Host $bits[0] `t`t $bits[1]
}
}
}
function hosts {
try {
if ($args[0] -eq "add") {
if ($args.count -lt 3) {
throw "Not enough arguments for add."
} else {
add-host $file $args[1] $args[2]
}
} elseif ($args[0] -eq "remove") {
if ($args.count -lt 2) {
throw "Not enough arguments for remove."
} else {
remove-host $file $args[1]
}
} elseif ($args[0] -eq "show") {
print-hosts $file
} elseif ($args[0] -eq "edit") {
edit-hosts $file
} else {
throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show'."
}
} catch {
Write-Host $error[0]
Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment