Last active
January 5, 2020 16:47
-
-
Save LoveDuckie/7a1da6cfdb7aa265d097cf5231ea4307 to your computer and use it in GitHub Desktop.
PowerShell function for updating hosts file on Windows.
This file contains hidden or 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
| <# | |
| Check using a regex pattern whether or not the domain is considered valid. | |
| #> | |
| function Test-WebsiteDomainValid | |
| { | |
| Param([Parameter(Mandatory=$True,HelpMessage="Determine if the domain name for the website is considered valid.")][string]$WebsiteDomainName) | |
| return [Text.Regex]::IsMatch($WebsiteDomainName,"[^a-zA-Z0-9\-]+") | |
| } | |
| <# | |
| Update the hosts file on the system so that it specifies our new website domain name. | |
| This function might fail if this script is not running as admin. | |
| #> | |
| function Update-SystemHostsFile() | |
| { | |
| Param( | |
| [Parameter(HelpMessage="The domain name for the website to update the hosts file with.",Mandatory=$True)][string]$WebsiteDomainName, | |
| [Parameter(HelpMessage="The target to update the hosts file with.",Mandatory=$True)][string]$Target | |
| ) | |
| $HostsFilePath="C:\Windows\System32\drivers\etc\hosts" | |
| $HostsFileContents=Get-Item -Path $HostsFilePath -Force | |
| if ((Test-WebsiteDomainValid -WebsiteDomainName $WebsiteDomainName) -ne $True) | |
| { | |
| Write-Error "Failed: the website domain name ""${WebsiteDomainName}"" is invalid." -ErrorAction Stop | |
| return $False | |
| } | |
| if ([string]::IsNullOrEmpty($HostsFileContents)) | |
| { | |
| Write-Error "Failed: the hosts file is empty or null. Check the path ""${HostsFilePath}""" -ErrorAction Stop | |
| return $False | |
| } | |
| Write-Host "Updating: system hosts file ""${WebsiteDomainName}"" -> ""${Target}""" | |
| if ($HostsFileContents.Contains($WebsiteDomainName) -eq $False) | |
| { | |
| $SiteAppend="${WebsiteDomainName} ${Target}" | |
| $SiteAppend | Out-File -FilePath $HostsFilePath -Force -Append | |
| } | |
| } | |
| Update-SystemHostsFile -WebsiteDomainName "arcanedreams.local" "127.0.0.1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment