Skip to content

Instantly share code, notes, and snippets.

@takase1121
Created October 6, 2019 16:30
Show Gist options
  • Save takase1121/773a26e9894bbdbfdbc7090d0bb67aeb to your computer and use it in GitHub Desktop.
Save takase1121/773a26e9894bbdbfdbc7090d0bb67aeb to your computer and use it in GitHub Desktop.
PowerShell Script to change host file for WSL2
$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
}
@takase1121
Copy link
Author

takase1121 commented Oct 6, 2019

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:

  • multiple IPs

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment