Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sunnyc7/8617525 to your computer and use it in GitHub Desktop.
Save sunnyc7/8617525 to your computer and use it in GitHub Desktop.
#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