Last active
August 24, 2017 20:13
-
-
Save MarkTiedemann/8b065883cd76f91752a4dd2167053dc4 to your computer and use it in GitHub Desktop.
Manage Windows hosts file from command line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@echo off | |
powershell -f %~dp0hosts.ps1 %1 %2 %3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Usage: