Last active
December 20, 2015 10:59
-
-
Save jstangroome/6119894 to your computer and use it in GitHub Desktop.
Proof-of-concept for parsing "#CNAME" comments in a HOSTS file to auto-replace IP addresses
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
#requires -version 3 | |
[CmdletBinding()] | |
param () | |
$DatabasePath = Get-CimInstance -ClassName Win32_NetworkAdapterConfiguration -Filter 'DatabasePath is not null' -Property DatabasePath | | |
Select-Object -ExpandProperty DatabasePath -First 1 | |
$DatabasePath = [Environment]::ExpandEnvironmentVariables($DatabasePath) | |
$HostsFilePath = Join-Path -Path $DatabasePath -ChildPath HOSTS | |
$Pattern = '^\s*(?<ip>\d+\.\d+\.\d+\.\d+)\s+[^#]*#CNAME\s+(?<fqdn>[^\s]+)\s*$' | |
(Get-Content -Path $HostsFilePath) | | |
ForEach-Object { | |
if ($_ -match $Pattern) { | |
$IPv4Address = [System.Net.Dns]::Resolve($Matches.fqdn).AddressList | | |
Where-Object { $_.AddressFamily -eq 'InterNetwork' <# ipv4 #> } | | |
Select-Object -First 1 | |
$_ -replace ('^\s*' + [Regex]::Escape($Matches.ip)), $IPv4Address.ToString() | |
} else { | |
$_ | |
} | |
} | Set-Content -Path $HostsFilePath -Encoding ASCII |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment