Created
June 28, 2021 11:04
-
-
Save InventivetalentDev/eb8332662fcb309e6702dd24edf39ea1 to your computer and use it in GitHub Desktop.
Powershell script to auto-alias the current WSL IP to a hostname
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
# Adapted from https://community.spiceworks.com/topic/1583047-how-to-update-host-file-automatically-by-batch-file | |
if ($args.Count -lt 2) | |
{ | |
"wslhost (distro name) (hostname) [actually write]" | |
wsl --list | |
return; | |
} | |
$distro = $args[0] | |
$targethost = $args[1] | |
$ip = $( wsl -d $distro hostname -I ) | |
$pattern = '^*' + $targethost + '.*$' | |
$file = "$( $env:SystemRoot )\System32\drivers\etc\hosts" | |
$hosts = Get-Content -Path $file | |
"$ip $targethost" | |
$hosts = $hosts | Foreach { | |
if ($_ -match $pattern) | |
{ | |
# Replace line | |
"$ip $targethost" | |
} | |
else | |
{ | |
# Keep current line | |
$_ | |
} | |
} | |
if ($args[2] -eq "write" -or $args[2] -eq "true") | |
{ | |
$hosts | Out-File $file -enc ASCII | |
"Written to System32\drivers\etc\hosts" | |
} | |
else | |
{ | |
$hosts | |
"Use 'wslhost $distro $targethost write' to write to the hosts file (requires elevated privileges)" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment