Skip to content

Instantly share code, notes, and snippets.

@InventivetalentDev
Created June 28, 2021 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InventivetalentDev/eb8332662fcb309e6702dd24edf39ea1 to your computer and use it in GitHub Desktop.
Save InventivetalentDev/eb8332662fcb309e6702dd24edf39ea1 to your computer and use it in GitHub Desktop.
Powershell script to auto-alias the current WSL IP to a hostname
# 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