Skip to content

Instantly share code, notes, and snippets.

@nichollsc81
Last active May 20, 2021 13:24
Show Gist options
  • Save nichollsc81/2603eb3de85960628efefd6241ca0320 to your computer and use it in GitHub Desktop.
Save nichollsc81/2603eb3de85960628efefd6241ca0320 to your computer and use it in GitHub Desktop.
Adds record to hosts file
# credit Tom Chantler: https://github.com/TomChantler/EditHosts
function Add-RecordToHosts
{
[cmdletbinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[ValidatePattern('^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$')]
[string[]] $DesiredIP,
[Parameter(Mandatory = $true, Position = 1)]
[ValidateNotNullOrEmpty()]
[string[]] $Hostname,
[Parameter(Position = 2)]
[bool] $CheckHostnameOnly = $false
)
begin
{
$ErrorActionPreference = 'Stop'
if (! ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "Function requires elevation."
Break
}
$hostsFilePath = "$($env:WinDir)\system32\Drivers\etc\hosts"
$hostsFile = (Get-Content $hostsFilePath)
Write-Verbose "Adding $desiredIP for $Hostname to hosts file"
}
process
{
$escapedHostname = [Regex]::Escape($Hostname)
$patternToMatch = If ($CheckHostnameOnly) { ".*\s+$escapedHostname.*" } Else { ".*$DesiredIP\s+$escapedHostname.*" }
if (($hostsFile) -match $patternToMatch)
{
Write-Host "$DesiredIp $Hostname - not adding; already in hosts file"
}
else
{
Write-Verbose "$DesiredIp $Hostname - adding to hosts file... "
Add-Content -Encoding UTF8 $hostsFilePath ("`n$DesiredIP" + ' ' + "$Hostname") -NoNewLine
Write-Host "Added."
}
}
}
#Add-RecordToHosts 8.8.8.8 www.google.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment