Created
October 6, 2019 16:30
-
-
Save takase1121/773a26e9894bbdbfdbc7090d0bb67aeb to your computer and use it in GitHub Desktop.
PowerShell Script to change host file for WSL2
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
$global:currentIP = "" | |
function checkAndEdit() { | |
$wslOutput = & "C:\Windows\System32\wsl.exe" -l -q --running | |
if ($LASTEXITCODE -ne 0) { | |
Write-Output "Failed to get WSL status" | |
} else { | |
if ([string]::IsNullOrEmpty($wslOutput)) { | |
# no output, not running | |
Write-Output "WSL is not running, no changes needed" | |
return | |
} else { | |
$ip = getHosts | |
if ($ip -ne $global:currentIP) { | |
$global:currentIP = $ip | |
replaceHostFile($ip) | |
} | |
} | |
} | |
} | |
function getHosts() { | |
$bashOutput = & "C:\Windows\System32\bash.exe" -c "hostname -I" | |
return $bashOutput.split(" ")[0] | |
} | |
function replaceHostFile($ip) { | |
$textArr = "" | |
foreach ($line in Get-Content "C:\Windows\System32\drivers\etc\hosts") { | |
if ($line -match "# WSL2 DO NOT EDIT THIS LINE") { | |
# dont copy if it was already set | |
} else { | |
$textArr = if ([string]::IsNullOrEmpty($textArr)) { $textArr + $line } else { $textArr + "`n" + $line } | |
} | |
} | |
$textArr = $textArr + "`n" + $ip + " " + "wsl.local # WSL2 DO NOT EDIT THIS LINE" | |
$textArr > "C:\Windows\System32\drivers\etc\hosts" | |
Write-Output "Done!" | |
} | |
While (1) { | |
if (Test-Path "C:\Windows\System32\wsl.exe") { | |
checkAndEdit | |
} else { | |
Write-Output "You don't have WSL installed" | |
} | |
Start-Sleep -Seconds 5 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A very simple PowerShell script to change hosts automatically when WSL2 is running. It changes the stuff automatically when an WSL2 instance starts.
currently not supporting:
NOTE: this is not guaranteed to work. While it worked for me, the performance is pitiful. I will improve it some time later, but definitely not now.