Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Last active August 24, 2017 20:13
Show Gist options
  • Save MarkTiedemann/8b065883cd76f91752a4dd2167053dc4 to your computer and use it in GitHub Desktop.
Save MarkTiedemann/8b065883cd76f91752a4dd2167053dc4 to your computer and use it in GitHub Desktop.
Manage Windows hosts file from command line
@echo off
powershell -f %~dp0hosts.ps1 %1 %2 %3
$file = 'C:\Windows\System32\drivers\etc\hosts'
function _ls () {
get-content $file |
% { $_.trim() } |
where { $_ -ne '' } |
where { !$_.startswith('#') } |
% {
($_.split(' ') |
% { $_.trim() } |
where { $_ -ne '' } |
select -first 2) `
-join ' '
}
}
function _add ($a, $b) {
if (!$b) { add-content $file "127.0.0.1 $a" }
else { add-content $file "$a $b" }
}
function _rm ($a, $b) {
set-content $file (get-content $file | where {
if (!$_.startswith('#')) {
if ($a -and !$b) { $_ -notlike "*$a*" }
if ($a -and $b) { $_ -notlike "*$a*$b*" }
} else { $true }
})
}
if ($args[0] -eq 'add') { _add $args[1] $args[2] }
if ($args[0] -eq 'rm') { _rm $args[1] $args[2] }
_ls
@MarkTiedemann
Copy link
Author

Example Usage:

λ hosts

λ hosts add dev
127.0.0.1 dev

λ hosts add local
127.0.0.1 dev
127.0.0.1 local

λ hosts rm local
127.0.0.1 dev

λ hosts
127.0.0.1 dev

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment