Skip to content

Instantly share code, notes, and snippets.

@gavi
Created January 18, 2019 21:04
Show Gist options
  • Save gavi/de180fdcfcd6b4cc4b1479974688d0f1 to your computer and use it in GitHub Desktop.
Save gavi/de180fdcfcd6b4cc4b1479974688d0f1 to your computer and use it in GitHub Desktop.
Add host entry to windows host file
function AddHostEntry($fqdn){
$Pattern = '^(?<IP>\d{1,3}(\.\d{1,3}){3})\s+(?<Host>.+)$'
$File = "$env:SystemDrive\Windows\System32\Drivers\etc\hosts"
$Entries = @()
$found = $false
(Get-Content -Path $File) | ForEach-Object {
If ($_ -match $Pattern) {
#Write-Host "$($Matches.IP),$($Matches.Host)" -ForegroundColor Green
if($Matches.Host -eq $fqdn){
$found = $true
}
}
}
if($found){
Write-Host "Entry Exists" -ForegroundColor Green
}
else{
Write-Host "Adding Entry $($fqdn)" -ForegroundColor Green
Add-Content $File "`r`127.0.0.1 $($fqdn) "
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment