Created
June 5, 2020 07:46
-
-
Save MichaelBelgium/2243e5713833ba44b5675d844eeb1c85 to your computer and use it in GitHub Desktop.
WSL v2 windows hosts sync (powershell - updates domains to wsl2 ip)
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 -RunAsAdministrator | |
# Only works for WSL v2, this is completely not needed for WSL v1 where u always can use 127.0.0.1 in hosts file | |
Clear-Host | |
if ((Get-InstalledModule "Carbon" -ErrorAction SilentlyContinue) -eq $null) { | |
Install-Module -Name 'Carbon' -AllowClobber | |
} | |
Import-Module 'Carbon' | |
$wslIp = (wsl hostname -I) -replace ' ','' | |
Write-Host "Setting wsl v2 hosts entries to $wslIp" | |
$domains = @( | |
'wsl2.local' | |
# add more domains if necessary | |
) | |
foreach($domain in $domains) { | |
Set-HostsEntry -IPAddress $wslIp -HostName $domain | |
} | |
Write-Host "Done!" |
Amazing. Thank you. It's perfect for my use case.
just for info, the @derik007 solution needs to use PowerShell as admin and execute "wsl", I've changed the last line :
vim "+:%s/^.*winip/$WINIP\t\twinip/g" "+:%s/^.*wslip/$WSLIP\t\twslip/g" '+:wq' -E /mnt/c/Windows/System32/drivers/etc/hosts
to
vi "+:%s/^.*wsl2.local/^$WSLIP wsl2.local/g" "+:wq" -E /mnt/c/Windows/System32/drivers/etc/hosts
I forked: https://gist.github.com/kakkun61/2139c240ac0dce1bb1606c1e8bc8038c
Added features:
- admin check
- run as admin
- install Carbon module if necessary
- remove old hosts entry
- multiple ip addr support
FWIW, my take can be found at https://gist.github.com/petski/1414048ca2db37592da2e7af13d718f5
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Guys!
The @derik007 bash version not working. :(
This is my version using Powershell; https://github.com/kallookoo/lamp/blob/feccb3e3c507f2d97afcc0962cb7e449ec0eeffb/src/win/hosts.ps1