Skip to content

Instantly share code, notes, and snippets.

@vidarl
Created May 21, 2021 08:45
Show Gist options
  • Save vidarl/8abe42b098bbaadf57f42049d8103818 to your computer and use it in GitHub Desktop.
Save vidarl/8abe42b098bbaadf57f42049d8103818 to your computer and use it in GitHub Desktop.
Add entry in windows' hosts file for wsl
# Execute using:
# powershell -ExecutionPolicy Bypass -File .\wsl_ip.ps1
# You need to make sure current user has write access to c:\Windows\system32\Drivers\etc\hosts
#source :
#https://github.com/microsoft/WSL/issues/4210#issuecomment-788729288
#https://github.com/vprokofyev/powershell/blob/main/wsl2-scripts/wsl_ip.ps1
# Then changed by VL
$ErrorActionPreference = "Stop"
# Make sure you backed up $windir\system32\Drivers\etc\hosts
# Get ip from wsl, thanks Rakasch
$wsl_ip = wsl hostname -I
$new_entry = $wsl_ip + "wsl"
# Path to hosts file
$hostsFile = "$($env:windir)\system32\Drivers\etc\hosts"
$hostsFileBackup = "D:\hosts.backup"
if (-not(Test-Path -Path $hostsFileBackup -PathType Leaf)) {
Write-Output "Making backup"
cp $hostsFile $hostsFileBackup
} else {
Write-Output "Recovering backup"
cp $hostsFileBackup $hostsFile
Write-Output "Restored backup"
}
# Read file and extract string with wsl ip-address if it is there
# org regexp:
#$regex_wsl_ip = '(172).\d{1,3}\.\d{1,3}\.\d{1,3}\b wsl'
#vl reg_exp:
$regex_wsl_ip = '^(172).* wsl$'
$wsl_string = (Get-Content -path $hostsFile | Select-String -Pattern "$regex_wsl_ip" -AllMatches).Matches.Value
# Check if string exists in file and rewrite it
if ($wsl_string) {
# Open file, replace strings, write
(Get-Content $hostsFile).Replace($wsl_string, $new_entry) | Set-Content $hostsFile
Write-Output "Rewrited $new_entry in $hostsFile"
}
else {
# Open file, add string, write
Add-Content -Path $hostsFile -Value $new_entry | Set-Content $hostsFile
Write-Output "Added $new_entry in $hostsFile"
}
# Delete backup file if we ever get here
if (Test-Path -Path $hostsFileBackup -PathType Leaf) {
Write-Output "Deleting backup file "
rm $hostsFileBackup
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment