Skip to content

Instantly share code, notes, and snippets.

@johnallers
Created December 23, 2021 18:56
Show Gist options
  • Save johnallers/ea78927989923039b43a5adad185eee6 to your computer and use it in GitHub Desktop.
Save johnallers/ea78927989923039b43a5adad185eee6 to your computer and use it in GitHub Desktop.
Sets wsl2.local in HOSTS file to current WSL2 IP
$wsl2IP = (wsl hostname -I).Split(" ")[0]
Write-Host "Setting wsl2.local IP to the WSL2 IP ($wsl2IP)"
$hostsPath = "$env:windir\System32\drivers\etc\hosts"
$dockerHostsPattern = '^((\d{1,3}\.){3}\d{1,3}) wsl2\.local$'
$hosts = get-content $hostsPath
$hosts = $hosts | Foreach {
if ($_ -match $dockerHostsPattern)
{
$oldIP = $Matches.1
"$wsl2IP wsl2.local"
} else {$_}}
if ($oldIP -eq $wsl2IP){
Write-Host "No change"
}
else {
[System.IO.File]::Copy($hostsPath, $hostsPath + ".bak", $true)
$hosts | Out-File $hostsPath -Encoding ascii
Write-Host "Updated"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment