|
$file = "C:\Windows\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 Find-Hostname([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 search-hosts([string]$filename, [string]$hostname){ |
|
$c = Get-Content $filename |
|
$count = 0; |
|
$hostname = '*'+$hostname+'*' |
|
Write-Host "Searching for "$hostname |
|
foreach ($line in $c) { |
|
$bits = [regex]::Split($line, "\t+") |
|
if ($bits.count -eq 2) { |
|
if($bits[0] -like $hostname -or $bits[1] -like $hostname) { |
|
$count++; |
|
Write-Host $bits[0] `t`t $bits[1] |
|
} |
|
} |
|
} |
|
if($count -eq 0){ |
|
Write-Host "No results" |
|
} |
|
} |
|
|
|
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") { |
|
gc $file |
|
} elseif ($args[0] -eq "open"){ |
|
try { |
|
Start-Process 'C:\Program Files (x86)\Notepad++\notepad++.exe' $file |
|
} |
|
catch { |
|
Start-Process 'notepad.exe' $file |
|
} |
|
} elseif($args[0] -eq "search"){ |
|
Write-Host 'test' |
|
Find-Hostname $file $args[1] |
|
} |
|
|
|
else { |
|
throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show', 'search + [hosts]' or 'open'." |
|
} |
|
} catch { |
|
Write-Host $error[0] |
|
Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show`n hosts search <hostname>`n hosts open" |
|
} |
Broken. To start with, there is no such thing as
print-hosts $file
, replace it withgc $file
.