Skip to content

Instantly share code, notes, and snippets.

@todiadiyatmo
Created May 7, 2023 13:45
Show Gist options
  • Save todiadiyatmo/3ab9ea76b47574be509bcaf50f349dce to your computer and use it in GitHub Desktop.
Save todiadiyatmo/3ab9ea76b47574be509bcaf50f349dce to your computer and use it in GitHub Desktop.
WSL Hostname
$HostAddr = wsl.exe -e ip addr show eth0 | Select-String -Pattern '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' | % { $_.Matches.Value }
# using Env:WinDir just in case our Windows folder is not on C: drive
$hostsFilePath = $Env:WinDir+'\system32\Drivers\etc\hosts'
# Hostname(s) being added, space delimited
$hostNames = "wsl.local"
# Obviously special characters like spaces and periods need to be escaped
$escapedHostNames = [Regex]::Escape($HostNames)
# Remove old IP for the host name(s)
(Get-Content $hostsFilePath) -notmatch ".*\s+$escapedHostNames.*" | Out-File $hostsFilePath
# Add current IP for the host name(s). Padding is strictly for visual alignment and is not necessary
Add-Content -Encoding UTF8 $hostsFilePath ("$HostAddr".PadRight(16, " ") + $hostNames)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment