Giter Site home page Giter Site logo

wikiped / wsl-iphandler Goto Github PK

View Code? Open in Web Editor NEW
55.0 2.0 5.0 252 KB

Powershell module which aims to provide a way to manage IP addresses for WSL SubNet and WSL Instances.

License: MIT License

PowerShell 94.29% Shell 5.71%
windows-10 wsl2 network powershell ipaddress

wsl-iphandler's Introduction

WSL IP Handler

CONTENT

Overview

Prerequisites

How to get this module?

Where the module is installed?

How does it work?

  WSL2 Configuration Requirements

  How On-Demand mode works?

  How On-Logon mode works?

  What happens during WSL Instance startup?

  What happens when WSL Hyper-V Network Adapter is being setup?

  Powershell Profile Modification

How to use this module?

How to deactivate this module?

How to update this module?

How to completely remove this module?

How to enable Unicode UTF-8 support on Windows?

Getting help

Credits

What's new?


Overview

This project is an attempt to address WSL networking issues that can be viewed in details in numerous posts over several long standing issues at WSL project. Here are a couple of them:

Main points of frustration are:

  1. WSL SubNet is changing after every Windows system reboot varying within wide range of Private IPv4 addresses: 172.16.0.0/12, 192.168.0.0/16, 10.0.0.0/8.

  2. All running WSL Instances have the same random IP address within WSL SubNet although default SubNet prefix length for some reason is 16 (which is enough for 65538 ip addresses!).

  3. There is no documented way to control IP address of WSL network adapter and / or of a specific WSL instance.

WSL IP Handler is a Powershell Module which puts together several of the "fixes" / scripts that have been posted over time in the issues mentioned above and aims to provide easy, percistant and automated control over:

  1. IPv4 properties of vEthernet (WSL) network adapter.

  2. IP addresses assignments within WSL SubNet to WSL instances.

  3. DNS resolution for Windows host and WSL instances within WSL SubNet.

In other words what WSL should have been doing out-of-the-box.


Prerequisites

  1. Windows 10.

    Please be aware that the module is not being tested to work on Windows 11. Which does not mean it will not work, but since Windows 11 introduced new WSL features this might affect how the module operates.

  2. PowerShell 7.1+.

    How to install Powershell Core.

  3. WSL 2 enabled / installed.

    This module is not being tested to work with WSL 1

  4. Administrative access on the windows machine, where the module will be used.

  5. Ubuntu or Fedora family OS as WSL instance.

    Other versions might work, but the module is being tested only with the above two.

  6. Unicode UTF-8 support enabled in Windows Settings.


How to get this module

To download and copy the module to Modules folder of Powershell profile for Current User run the following commands from Powershell prompt:

Universal web installer

Command below will download the installation script and will prompt you to choose whether to use git.exe (if git can be found in PATH) or use zippied repository:

Invoke-WebRequest https://raw.githubusercontent.com/wikiped/Wsl-IpHandler/master/Install-WslIpHandlerFromGithub.ps1 | Select -ExpandProperty Content | Invoke-Expression

Otherwise you can use any of the below two methods to install the module.

If Git is installed

New-Item "$(split-path $Profile)\Modules" -Type Directory -ea SilentlyContinue
cd "$(split-path $Profile)\Modules"
git clone https://github.com/wikiped/Wsl-IpHandler

If Git is NOT installed

New-Item "$(split-path $Profile)\Modules" -Type Directory -ea SilentlyContinue
cd "$(split-path $Profile)\Modules"
Invoke-WebRequest -Uri https://codeload.github.com/wikiped/Wsl-IpHandler/zip/refs/heads/master -OutFile 'Wsl-IpHandler.zip'
Expand-Archive -Path 'Wsl-IpHandler.zip' -DestinationPath '.'
Remove-Item -Path 'Wsl-IpHandler.zip'
Rename-Item -Path 'Wsl-IpHandler-master' -NewName 'Wsl-IpHandler'

Where the module is installed?

After executing above commands in How to get this module the module is installed in a Powershell profile directory for the current user.

Run Split-Path $Profile to see location of the profile directory.

When Import-Module SomeModule command is executed, Powershell looks for SomeModule in this directory (among others).

It is important to be aware of the fact that WSL2 does not yet support windows network shares within linux, so if the module is installed on a network share it will NOT be working correctly. To mitigate this issue the module checks where it is installed and warns the user of the problem.


How does it work?

When WSL IP Handler is activated (with Install-WslIpHandler command) it stores required network configuration in ~\.wsl-iphandler-config file. This configuration is then used by Powershell scripts on Windows host and Bash scripts on WSL Instance where it has been activated to ensure IP Addresses determinism.

There are two ways how IP Address persistance of WSL Hyper-V Network Adapter can be achieved with this module:

  • On-Demand: The adapter is created (if it is not present) or modified (if was created beforehand by Windows) to match the required network configuration when the user runs wsl command through Powershell session.

  • On-Logon: The adapter is created by a Scheduled Task that runs on user logon. This way the user does not have to use Powershell (interactively) to ensure WSL adapter's network configuration matches required.

The following sections describe which files are modified (outside of module's directory) on Windows host and WSL instance(s).


WSL2 Configuration Requirements

WSL uses two configuration files:

  • ~/.wslconfig on Windows

  • /etc/wsl.conf on Linux

Wsl-IpHandler module requires default configuration of some of the settings of /etc/wsl.conf to work correctly (settings below do not have to be present in the file!):

[interop]
enabled = true
appendWindowsPath = true
[automount]
enabled = true
[network]
generateResolvConf = true

On Windows side in ~\.wslconfig there is one setting which has side effect on WSL2 networking and which affects this module operation:

[wsl2]
swap = ...

The problem appears when swap setting is enabled and the swap file in use is using NTFS compression. This is a known WSL2 issue (#4731, #5286, #5336, #5437) causing linux eth0 interface to be in a DOWN state when WSL instance starts. This makes the WSL network unavailable and hence the module non-operational.

The solution to this problem is to either disable swap or disable NTFS compression on a swap file. This module by default opts for disabling swap in .wslconfig:

[wsl2]
swap = 0

For these reasons the module validates WSL configuration both on windows side and linux side to ensure correct behavior.


Files created or modified on Windows Host (outside of modules directory)

  • File modified during module activation: ~\.wsl-iphandler-config
  • File modified (if necessary) during module activation: ~\.wslconfig
  • File modified (optionally) during module activation: $Profile.CurrentUserAllHosts (Powershell Profile file)
  • File modified (if necessary) during startup of WSL Instance: %WINDOWS%\System32\Drivers\etc\hosts

Files created or modified on WSL Instance system

  • New file created during module activation: /usr/local/bin/wsl-iphandler.sh
  • New file created during module activation: /etc/profile.d/run-wsl-iphandler.sh
  • New file created during module activation: /etc/sudoers.d/wsl-iphandler
  • New file created during module activation: /etc/wsl-iphandler.conf
  • File modified (if necessary) during module activation: /etc/wsl.conf
  • File modified (if necessary) during startup of WSL Instance: /etc/hosts

Files modified during Module Activation

  • Bash scripts are copied to the specified WSL Instance and /etc/wsl-iphandler.conf file is used to save Windows host name.
  • Network configuration parameters are saved to ~\.wsl-iphandler-config on Windows host:
    • In Static Mode if WSL Instance IP address is not specified - the first available IP address will be selected automatically;
    • In Dynamic Mode IP address offset (1-254) will be selected automatically based on those already used (if any) or 1;
  • Powershell profile file is modified (if not opted out) to ensure on demand availability of WSL Hyper-V Network Adapter with required configuration.
  • New Scheduled Task created (optionally) to ensure WSL Hyper-V Network Adapter is configured at logon.

How On-Demand mode works?

When wsl alias is executed from Powershell prompt:

  • All arguments of the call are checked for presence of "informational" parameters (i.e. those parameters that do not require launch (initialization) of WSL Instance).
    • If present:
      • wsl.exe is executed with all arguments passed 'as is'.
    • Otherwise:
      • ~\.wsl-iphandler-config is checked for Gateway IP Address:
        • If found - Static Mode detected:
          • If WSL Hyper-V Adapter is present - it is checked to have network properties matching those saved during activation. If there is a mismatch - adapter is removed and new one created.
          • If adapter is not present - it is created.
      • wsl.exe is executed with all arguments passed 'as is'.
    • Before starting wsl.exe and after WSL Network Adapter had to be created the module will poll for vEthernet (WSL) Network Connection availability every 3 seconds and when network connection becomes available then actually invoke wsl.exe. There is a timeout of 30 seconds to wait for the connection to become available.
    • If vEthernet (WSL) Network Connection is not available after specified Timeout (30 seconds by default) Exception will be thrown.
    • Timeout can be changed by setting -Timeout parameter: wsl -Timeout 60.

Note that wsl command (not the same as wsl.exe) in this section refers to Powershell Alias that is created by this module and which is available only when this module is imported into current Powershell session, either manually or automatically through modified Powershell profile.


How On-Logon mode works?

When Install-WslIpHandler is executed with parameter -UseScheduledTaskOnUserLogOn the module creates a new Scheduled Task named Wsl-IpHandlerTask under Wsl-IpHandler folder. The task has a trigger to run at user logon.

If parameter -AnyUserLogOn was specified to Install-WslIpHandler (along with -UseScheduledTaskOnUserLogOn) then the task will run at logon of ANY user. Otherwise the task will run only at logon of specific user - the one who executed Install-WslIpHandler command.

Since Scheduled Task runs the script in non-interactive mode in a hidden terminal window there will be no usual messages from the script. To be informed of the success/failures during execution of Scheduled Task there are Toast Notifications which are enabled by default when Install-WslIpHandler is executed with parameter -UseScheduledTaskOnUserLogOn. To disable toast notifications run Set-WslScheduledTask without -ShowToast parameter. See Get-Help Set-WslScheduledTask for more information.

Note that it takes some time for Windows to execute its startup process (including logon tasks among other things). So it will take some time before WSL Hyper-V Network Adapter will become available.


What happens during WSL Instance startup?

IP Address handling at WSL instance's side is done with user's profile file modification. Therefore it will not work when WSL instance has been launched after wsl.exe --shutdown with a command like this: wsl ping windows.host (which is an example of non-interactive session). The reason for this is that Bash does not execute user's profile script in non-interactive sessions.

In all other cases when wsl is executed to open a terminal (i.e. interactive session) profile script will run:

  • Bash script wsl-iphandler.sh will be executed to:
    • Add WSL Instance IP address to eth0 interface. In Dynamic Mode IP address is obtained first from IP offset and Windows Host gateway IP address.
    • Add Windows host gateway IP address to /etc/hosts if not already added.
    • Run Powershell script on Windows host to add WSL Instance IP address with its name to Windows hosts if not already added.

A workaround to ensure execution of profile script in non-interactive Bash session is to run command like this (from Powershell):

wsl.exe -e env BASH_ENV=/etc/profile bash -c 'ping windows.host'

What happens when WSL Hyper-V Network Adapter is being setup?

Regardless of whether the module operates in On-Demand or On-Logon mode there a several steps taken to ensure the adapter is properly configured:

  1. Check if the adapter exists and is already configured as required. If yes - nothing is done.

  2. If the adapter does not exist yet or is mis-configured - it is removed (wsl --shutdown is executed beforehand).

  3. Check if there are any other network connections having IP network configuration that overlaps (conflicts) with the one specified for WSL adater (through parameters or from ~\.wsl-iphandler-config file).

  4. If there are conflicts and overlapping network is from one of Hyper-V adapters (Ethernet or Default Switch) - conflicting adapter will be recreated to take IP network subnet that does not conflict with WSL Adapter.

  5. Any other conflicting network will cause the module to throw an error and it is up to the user to either choose a different IP Subnet for WSL adapter of reconfigure IP settings of conflicting network connection.

  6. When no conflicts are found (or they have been resolved) WSL adapter is created.


Powershell Profile Modification

By default, if Static mode of operation has been specified, activation script will modify Powershell profile file (by default $Profile.CurrentUserAllHosts). The only thing that is being added is wsl command alias. Actual command that will be executed is Invoke-WslExe. If modification of the profile is not desirable there is a parameter -DontModifyPsProfile to Install-WslIpHandler command to disable this feature.

To modify / restore profile manually at any time there is Set-ProfileContent and Remove-ProfileContent commands to add or remove modifications.

Created alias works ONLY from within Powershell sessions with user profile loading enabled (which is the default behavior).

See Execution of command alias for details on what happens when it is executed.

Profile modification takes effect after Powershell session restarts!


How to use this module?

Modes of operation

WSL IP Handler operates in two modes:

  • Dynamic
  • Static

Mode selection is based on configuration parameters provided when running activation command Install-WslIpHandler.

In table below No - means Parameter NOT specified and Yes - means Parameter has some value specified):

🡇 Parameter ⋰ Mode 🡆 Dynamic Static Invalid
GatewayIpAddress No Yes No
WslInstanceIpAddress No Yes | No Yes

Available capabilities depend on the Mode of operation:

🡇 Feature ⋰ Mode 🡆 Dynamic Static
Static WSL Network Adapter IP Address No Yes
Static WSL Instance IP Address No Yes
Unique IP Address of WSL Instance Yes Yes
DNS Records Yes Yes

In Static mode WSL IP Handler creates or replaces (if necessary) WSL Hyper-V Network adapter with properties specified during module activation.

In Dynamic mode WSL IP Handler does not interfere with how Windows manages WSL network properties.


Module Activation

  1. Import Module.

    Import-Module Wsl-IpHandler

    All commands that follow below require that the module has been imported with above command.

  2. Activate Module.

    • Activate in Dynamic Mode:

      Install-WslIpHandler Ubuntu
    • Activate in Static Mode:

      To get WSL Instance IP address assigned automatically:

      Install-WslIpHandler -WslInstanceName Ubuntu -GatewayIpAddress 172.16.0.1

      To assign static IP address to WSL Instance manually:

      Install-WslIpHandler -WslInstanceName Ubuntu -GatewayIpAddress 172.16.0.1 -WslInstanceIpAddress 172.16.0.2
    • Activate in Static Mode without modifying Powershell profile

      Install-WslIpHandler -WslInstanceName Ubuntu -GatewayIpAddress 172.16.0.1 -WslInstanceIpAddress 172.16.0.2 -DontModifyPsProfile
    • Activate in Static Mode without modifying Powershell profile and enabling WSL adapter setup during logon

      Install-WslIpHandler -WslInstanceName Ubuntu -GatewayIpAddress 172.16.0.1 -WslInstanceIpAddress 172.16.0.2 -UseScheduledTaskOnUserLogOn -DontModifyPsProfile
  3. Use WSL Instance.

    Execute from Powershell prompt:

    (Feel free to reboot the computer or execute Remove-WslNetworkAdapter beforehand to see that the changes are persistent after system reboot)

    wsl -d Ubuntu

    From shell prompt within WSL Instanace of Ubuntu:

    > ping -c 1 windows
    PING windows (172.16.0.1) 56(84) bytes of data.
    64 bytes from windows (172.16.0.1): icmp_seq=1 ttl=128 time=0.417 ms
    
    --- windows ping statistics ---
    1 packets transmitted, 1 received, 0% packet loss, time 0ms
    rtt min/avg/max/mdev = 0.417/0.417/0.417/0.000 ms

    From Powershell in Windows Host:

    > ping -n 1 Ubuntu
    
    Pinging Ubuntu [172.16.0.2] with 32 bytes of data:
    Reply from 172.16.0.2: bytes=32 time<1ms TTL=64
    
    Ping statistics for 172.16.0.2:
        Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
    Approximate round trip times in milli-seconds:
        Minimum = 0ms, Maximum = 0ms, Average = 0ms
  4. Do I have to use Powershell to benefit from this module?

If Powershell is not part of day-to-day use it is still possible to benefit from this module's features.

Powershell is needed to 1) install (i.e. download) and 2) activate the module for all WSL instances where IP address control is required.

For this to work the module has to be activated with two switch parameters to Install-WslIpHandler:

Install-WslIpHandler <...other parameters...> -DontModifyPsProfile -UseScheduledTaskOnUserLogOn

This will setup WSL Hyper-V Network Adapter configuration during user logon, without any need to use Powershell to start any WSL instance.


How to deactivate this module?

From Powershell prompt execute:

Uninstall-WslIpHandler -WslInstanceName Ubuntu

If WSL Instance being removed had Static IP address and it is the only one remaining all network configuration settings (Windows Host Name and Gataway IP Address) will also be removed along with Scheduled Task and Powershell profile modifications.

Even after Wsl-IpHandler was deactivated on all WSL instances WSL Hyper-V Network Adapter will remain active until next reboot or manual removal with Remove-WslNetworkAdapter command.


How to update this module

To update this module to the latest version in github repository run in Powershell prompt:

Update-WslIpHandlerModule

How to completely remove this module

Before completely removing the module it is recommended to make sure the module has been deactivated on all WSL instances.

To remove the module - delete the module's folder. It's location can be checked with:

(Import-Module Wsl-IpHandler -PassThru | Get-Module).ModuleBase

Or execute from Powershell prompt:

Import-Module Wsl-IpHandler
Uninstall-WslIpHandlerModule

How to enable Unicode UTF-8 support on Windows

Run / Execute command:

control international

Then in the opened window select tab: Administrative -> Change system locale...

Select option Beta: Use Unicode UTF-8 for worldwide language support in the opened window.


Getting Help

To see list of all available commands from this module, execute in Powershell::

Get-Command -Module Wsl-IpHandler

To get help on any of the commands, execute Get-Help <Command-Name>, i.e.:

Get-Help Install-WslIpHandler

To get help on a particular parameter of a command add -Parameter <ParameterName>, i.e.:

Get-Help Install-WslIpHandler -Parameter UseScheduledTaskOnUserLogOn

Credits

This module is using the code (sometimes partially or with modifications) from the following projects (in no particular order):

Create a known IP address for WSL2 VM by Biswa96

wsl2-custom-network by Sami Korhonen

wsl2ip2hosts by Jakob Wildrain

PsIni by Oliver Lipkau

IP-Calc by saw-friendship

wsl-iphandler's People

Contributors

amweiss avatar rsmarples avatar wikiped avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

wsl-iphandler's Issues

Error during install `'Import-Psd' is not recognized`

During installation I have this error on powershell 7.2.6:

Import-Psd: The term 'Import-Psd' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

But the module still loads and works as expected.

The property 'Error' cannot be found on this object at Wsl-IpHandler\FunctionsHNS.ps1:220

Hello,

At git commit 51f843c - Version 0.5.0.

I'm facing problems while trying to install this module on my WSL machine Ubuntu-20.04.

Could you please help me and possibly fix the issue?

First, to have PowerShell 7.1+, I installed PowerShell application from Microsoft Store (currently at version 1.0), then I opened the related PowerShell app as Administrator. Please confirm if this is a correct method.

Then to import the module, I needed to be in the directory where I cloned the repo, not in the repo itself, so this could work:

PS> Import-Module ./Wsl-IpHandler/Wsl-IpHandler.psd1 -Verbose
...
VERBOSE: Importing function 'Install-WslIpHandler'.
VERBOSE: Importing function 'Invoke-WslStatic'.
VERBOSE: Importing function 'Remove-ProfileContent'.
VERBOSE: Importing function 'Remove-WslInstanceStaticIpAddress'.
VERBOSE: Importing function 'Remove-WslNetworkAdapter'.
VERBOSE: Importing function 'Remove-WslNetworkConfig'.
VERBOSE: Importing function 'Set-ProfileContent'.
VERBOSE: Importing function 'Set-WslInstanceStaticIpAddress'.
VERBOSE: Importing function 'Set-WslNetworkAdapter'.
VERBOSE: Importing function 'Set-WslNetworkConfig'.
VERBOSE: Importing function 'Test-WslInstallation'.
VERBOSE: Importing function 'Uninstall-WslIpHandler'.

I could discover that the README.md is wrong, so I patched it using following sed (in a GitBash).

# Rename "Install-Wsl-IpHandler" to "Install-WslIpHandler"
sed -i 's,Install-Wsl-IpHandler,Install-WslIpHandler,g' README.md

Now I am facing the following error.

PS> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.50.1 -WslInstanceIpAddress 192.168.50.2
PowerShell Installing WSL-IpHandler to Ubuntu-20.04...
ConvertResponseFromJsonEx: C:\Users\...\Wsl-IpHandler\FunctionsHNS.ps1:220
Line |
 220 |          $output += ConvertResponseFromJsonEx -JsonInput $properties
     |                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The property 'Error' cannot be found on this object. Verify that the property exists.

This is becoming out of my knowledge in PowerShell. Could you please help me?

Thanks you a lot in advance for your help,
Best regards,

Olivier

no Invoke-WslStatic

> wsl
wsl: The term 'Invoke-WslStatic' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

It was removed in v8.0.0 but still set as alias for wsl.

Install-WslIpHandler: error in creating scheduled task

Thanks for fixing the last issue I noticed!

When trying to run the latest version 0.11.4 2a63d12 I now get an error when the script tries to create the scheduled task..

Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 198.51.100.1 -WslInstanceIpAddress 198.51.100.1 -UseScheduledTaskOnUserLogOn -DontModifyPsProfile -Verbose
PowerShell installing WSL-IpHandler to Ubuntu-20.04...
VERBOSE: Hyper-V VM Adapter 'WSL' already exists.
VERBOSE: vEthernet (WSL) Network Connection Setup succeeded after [0] seconds.
VERBOSE: Setting Static IP Address: 198.51.100.1 for Ubuntu-20.04.
VERBOSE: Registering WSL-IpHandler scheduled task...
Set-WslScheduledTask: The variable '$commonParams' cannot be retrieved because it has not been set.

vEthernet (WSL) is not created after the on-logon job execution

I use static setup + on-logon scheduled task, which after reboot successfully completes (sometimes even calling out that WSL vSwitch had been already configured correctly) but no vEthernet (WSL) is seen via ipconfig. Then I start my WSL session and get default settings for vEthernet (something like 172.21.22... instead of static address I provided), so the WSL is set up with the address obviously not from required subnet and network is not working as expected.

The workaround I found it to delay scheduled task execution for 1 minute after logon.

Install-WslIpHandler rewrites profile.ps1

Wsl-IpHandler Content was added to Powershell profile: C:\Users\%User%\Documents\PowerShell\profile.ps1

Actually script not add, but replace all the file which lead to losing other settings. It should append the file.

Multiple WSL2 VMs maintain the same IP address

I've created multiple WSL2 VMs based on the latest ubuntu distro appx.

Whenever I change the IP address of one, it changes the IP address of them all.

PS C:\ [06:10:54]> wsl -l -v
  NAME                   STATE           VERSION
* kali-linux             Stopped         2
  ubuntu_control         Stopped         2
  ubuntu_workernode1     Stopped         2
  ubuntu_baseline        Stopped         2
  docker-desktop         Running         2
  docker-desktop-data    Stopped         2
  ubuntu_workernode2     Stopped         2
  ubuntu_workernode3     Stopped         2

PS C:\ [06:13:46]> Install-WslIpHandler -WslInstanceName ubuntu_control -GatewayIpAddress 192.168.143.1 -WslInstanceIpAddress 192.168.143.111
PowerShell installing Wsl-IpHandler to ubuntu_control...
Test of Wsl-IpHandler Installation on ubuntu_control Succeeded!
PowerShell successfully installed Wsl-IpHandler to ubuntu_control.

PS C:\ [06:14:01]> wsl -d ubuntu_control hostname -I
192.168.143.111

PS C:\ [06:14:25]> Install-WslIpHandler -WslInstanceName ubuntu_workernode1 -GatewayIpAddress 192.168.143.1 -WslInstanceIpAddress 192.168.143.112
PowerShell installing Wsl-IpHandler to ubuntu_workernode1...
Test of Wsl-IpHandler Installation on ubuntu_workernode1 Succeeded!
PowerShell successfully installed Wsl-IpHandler to ubuntu_workernode1.

PS C:\ [06:15:08]> wsl -d ubuntu_workernode1 hostname -I
192.168.143.112

PS C:\ [06:14:01]> wsl -d ubuntu_control hostname -I
192.168.143.112

PS C:\ [06:16:05]> wsl -d ubuntu_workernode2 hostname -I

Settings 'appendWindowsPath' in [interop] section is disabled in /etc/wsl.conf!
This setting must be enabled for Wsl-IpHandler to work. Please confirm if you want to continue:
[F] Fix  [N] No  [Y] Yes  [?] Help (default is "F"): f
192.168.143.112

PS C:\ [06:16:27]> wsl -d ubuntu_workernode3 hostname -I

Settings 'appendWindowsPath' in [interop] section is disabled in /etc/wsl.conf!
This setting must be enabled for Wsl-IpHandler to work. Please confirm if you want to continue:
[F] Fix  [N] No  [Y] Yes  [?] Help (default is "F"): f
192.168.143.112

PS C:\ [06:16:31]> wsl -d kali-linux hostname -I
cat: /etc/wsl.conf: No such file or directory
192.168.143.112

If I start an interactive shell with -d, the IP of all of the WSL2 VMs changes to the IP address of the last VM I've started a shell in.

It appears that this is discussed in detail with an example here. Note that as in, this only allows traffic to be routed across the bridge, which exists within the subsystem, therefore I don't believe it's accessible via a vSwitch in ICS.

Alone, this is still valuable. Can this be implemented?

Prefix length is not applied to WSL instance when operating in static mode

WSL IP Handler:
Install-WslIpHandler -GatewayIpAddress 10.0.0.1 -WslInstanceName Ubuntu -WslInstanceIpAddress 10.0.0.2 -UseScheduledTaskOnUserLogOn -DontModifyPsProfile
WSL (after reboot Windows):

$ ip addr
...
6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:c4:65:e4 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.2/32 scope global eth0:wsliphndlr
       valid_lft forever preferred_lft forever
    inet6 fe80::215:5dff:fec4:65e4/64 scope link
       valid_lft forever preferred_lft forever

As you can see, the prefix length is 32 rather than 24.

In wsl-iphandler.sh:

# Process Local IP and Host
local ip_address
ip_address=$(get_config 'static_ip' '')
echo_debug "ip_address=$ip_address"

# Get IP address for this WSL Instance
local wsl_ip_address
if [[ "$ip_address" ]]
then
	wsl_ip_address="$ip_address"
	echo_debug "wsl_ip_address=$wsl_ip_address"
else
	local gateway_ip
	gateway_ip=$(get_default_gateway_ip)
	test $? = 0 || error "${LINENO}" "'get_default_gateway_ip' failed." 10
	echo_debug "gateway_ip=$gateway_ip"

	local gateway_prefix
	gateway_prefix=$(get_gateway_prefix_length)
	test $? = 0 || error "${LINENO}" "'get_gateway_prefix_length' failed." 11
	echo_debug "gateway_prefix=$gateway_prefix"

	local gateway_ip_with_prefix
	gateway_ip_with_prefix="$gateway_ip/$gateway_prefix"
	test -n "$gateway_ip_with_prefix" || error "${LINENO}" "No gateway IP found!" 12
	echo_debug "gateway_ip_with_prefix=$gateway_ip_with_prefix"

	local offset
	offset=$(get_config 'ip_offset')
	echo_debug "offset=$offset"
	wsl_ip_address="$(get_new_ip_with_prefix_from_offset "$gateway_ip_with_prefix" "$offset")"
	echo_debug "wsl_ip_address=$wsl_ip_address"
fi

# Register new WSL Instance IP address (i.e. ip addr add ...)
echo_verbose "Adding IP: $wsl_ip_address to dev: $dev ..."
add_wsl_ip_address "$wsl_ip_address"

And /etc/wsl.conf:

$ cat /etc/wsl.conf
[network]
static_ip = 10.0.0.2
wsl_host = Ubuntu
windows_host = windows

As static_ip doesn't contain a prefix length, the add_wsl_ip_address will finally run ip addr add 10.0.0.2 ... and thus the prefix length will become 32.

It's easy to manually fix it by changing static_ip to 10.0.0.2/24. I‘m not sure whether it's by design or a bug, so I just report it here.

Why `Import-Module Wsl-IpHandler` if cloning into PowerShell Modules directory?

Hello,

Honestly I have a lot of difficulties to use this module. I felt this module is excellent because it is transparent with the wsl alias, so why I have put some effort to test it.


I don't understand the use of functions Import-Module Wsl-IpHandler and Uninstall-Module Wsl-IpHandler.

No need to import a module if already a module (already present in the PowerShell Modules directory).
Just open a new PowerShell and you'll see the module is usable.

If you made some changes, only force import the module to get the updated functions it provides in the current PowerShell.

For me, uninstalling the module never worked, wherever I cloned and however I imported it (see #3).


Update-WslIpHandlerModule makes the assumption we have git in the PATH.


The commit c56d7e3 brings regression. If you open a new shell and try either Install-WslIpHandler or Uninstall-WslIpHandler, it now complains there is no private data found.

This is a problem because if you closed the original PowerShell (like if you rebooted your Windows host), then you have no way to fix the situation with the commands.

Moreover if you stay in the original PowerShell, the wsl alias is not set.


The issue #6 is not fixed.

I understand that /usr/local/bin/wsl-iphandler.sh is not executed if you run a simple wsl command like I intended to use such as : wsl -u root service ssh start.

And you should merge #7 to fix this other little mistake.


I understand the DNS servername configuration is not under the control of this module. However, as a user, we need a solution that works.

Another drawback of this solution is it forces to use PowerShell 7.1+, it will be confusing for the users who still have PowerShell 5.1+ in my company.

PS: I am looking for the simplest solution to deploy WSL2 in my company.

Best regards,
Olivier

Import-Module: The specified module 'WSL-IpHandler' was not loaded because no valid module file was found in any module directory.

Hello,

With git commit 8ef8b3a - Fix spelling error in Readme.

Import-Module works only if specifying an absolute path.

At reboot, starting PowerShell 7.1+ as a normal user:

# Like described in README.md
PS> cd cd ~/git/github.com/WSL-IpHandler
PS> Import-Module WSL-IpHandler
Import-Module: The specified module 'WSL-IpHandler' was not loaded because no valid module file was found in any module directory.

# Now with a PATH in front:
PS> Import-Module ./WSL-IpHandler -Verbose
VERBOSE: Loading module from path 'C:\Users\crozier\git\github.com\WSL-IpHandler\WSL-IpHandler.psd1'.
VERBOSE: Importing function 'Install-WslIpHandler'.
VERBOSE: Importing function 'Invoke-WslStatic'.
VERBOSE: Importing function 'Remove-ProfileContent'.
VERBOSE: Importing function 'Remove-WslInstanceStaticIpAddress'.
VERBOSE: Importing function 'Remove-WslNetworkAdapter'.
VERBOSE: Importing function 'Remove-WslNetworkConfig'.
VERBOSE: Importing function 'Set-ProfileContent'.
VERBOSE: Importing function 'Set-WslInstanceStaticIpAddress'.
VERBOSE: Importing function 'Set-WslNetworkAdapter'.
VERBOSE: Importing function 'Set-WslNetworkConfig'.
VERBOSE: Importing function 'Test-WslInstallation'.
VERBOSE: Importing function 'Uninstall-WslIpHandler'.
VERBOSE: Importing function 'Update-WslIpHandlerModule'.

# To generate the next problem:
PS> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.50.1 -WslInstanceIpAddress 192.168.50.2
PowerShell Installing WSL-IpHandler to Ubuntu-20.04...
Bash Installing WSL-IpHandler...
Bash Installed wsl-iphandler!
PowerShell Successfully Installed WSL-IpHandler to Ubuntu-20.04.

This creates the file $Env:USERPROFILE/PowerShell/profile.ps1 with the following content:

# Start of WSL-IpHandler Section
Import-Module WSL-IpHandler -Force
Set-Alias wsl Invoke-WslStatic
# End of WSL-IpHandler Section

If starting another PowerShell 7.1+ as a normal user, I systematically get the following error:

Import-Module: C:\Users\crozier\Documents\PowerShell\profile.ps1:2
Line |
   2 |  Import-Module WSL-IpHandler -Force
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The specified module 'WSL-IpHandler' was not loaded because no valid module file was found in any module directory.

This problem is solved if I change the file with an absolute path like:

# Start of WSL-IpHandler Section
Import-Module $Env:USERPROFILE\git\github.com\WSL-IpHandler -Force
Set-Alias wsl Invoke-WslStatic
# End of WSL-IpHandler Section

But then, the Uninstall-WslIpHandler command fails to clean the file and leaves the following line:

Import-Module $Env:USERPROFILE\git\github.com\WSL-IpHandler -Force

Best regards,
Olivier

Error parsing windows hosts file: 'You cannot call a method on a null-valued expression' in Get-IpAddressHostsCommentTuple

PS C:\Users\Firsh> Install-WslIpHandler -WslInstanceName Ubuntu -GatewayIpAddress 172.16.0.1 -WslInstanceIpAddress 172.16.0.2 -UseScheduledTaskOnUserLogOn -DontModifyPsProfile
PowerShell installing Wsl-IpHandler to Ubuntu...
[sudo] password for firsh:
Get-IpAddressHostsCommentTuple: N:\Dokumentumok\PowerShell\Modules\Wsl-IpHandler\Scripts\Powershell\FunctionsHostsFile.ps1:261
Line |
 261 |  … stingIp, $existingHosts, $comment = Get-IpAddressHostsCommentTuple $_
     |                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | You cannot call a method on a null-valued expression.

PowerShell finished installation of Wsl-IpHandler to Ubuntu with Errors:

Pinging Ubuntu from Windows failed:
Ping request could not find host Ubuntu. Please check the name and try again.

Install-WslIpHandler: install-wsl-iphandler.sh not found

Using version 0.10.3 74b3db2

When running Install-WslIpHandler I get an error that the file install-wsl-iphandler.sh is not found.

The module continues to run but exits with an error saying: The variable '$fn' cannot be retrieved because it has not been set.

Looking in explorer.exe the file install-wsl-iphandler.sh is actually available in the PowerShell\Modules\Wsl-IpHandler-folder.

PS C:\Users\b92jkl> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 198.51.100.1 -WslInstanceIpAddress 198.51.100.1 -UseScheduledTaskOnUserLogOn -DontModifyPsProfile -Verbose
PowerShell installing WSL-IpHandler to Ubuntu-20.04...
VERBOSE: Set-WslNetworkAdapter Hyper-V VM Adapter 'WSL' already exists.
VERBOSE: Hyper-V VM Adapter 'WSL' already has required GatewayAddress: '198.51.100.1' and PrefixLength: '24'!
VERBOSE: Setting Static IP Address: 198.51.100.1 for Ubuntu-20.04.
VERBOSE: Importing function 'Get-IpNet'.
VERBOSE: Registering WSL-IpHandler scheduled task...
VERBOSE: Running Bash WSL installation script: Microsoft.PowerShell.Core\FileSystem::\\<SERVER>\<USER>\PowerShell\Modules\WSL-IpHandler\install-wsl-iphandler.sh
[sudo] password for <USER>:
bash: Microsoft.PowerShell.Core/FileSystem::/<SERVER>/<USER>/PowerShell/Modules/WSL-IpHandler/install-wsl-iphandler.sh: No such file or directory
VERBOSE: Terminating running instances of Ubuntu-20.04 ...
VERBOSE: Testing Activation of WSL IP Handler on Ubuntu-20.04 ...
VERBOSE: Testing Ping from WSL instance Ubuntu-20.04: "ping -c1 windows 2>&1" ...
VERBOSE: Ping from WSL Instance Ubuntu-20.04 failed:
ping: windows: Temporary failure in name resolution
VERBOSE: Testing Ping from Windows to WSL instance Ubuntu-20.04 ...
VERBOSE: Ping from Windows to WSL instance Ubuntu-20.04 failed:
Ping request could not find host Ubuntu-20.04. Please check the name and try again.
VERBOSE: Test-WslInstallation on Ubuntu-20.04 Failed!
PowerShell finished installation of WSL-IpHandler to Ubuntu-20.04 with Errors:
VERBOSE: Finished Testing Activation of WSL IP Handler.
Install-WslIpHandler: The variable '$fn' cannot be retrieved because it has not been set.

What is happening here and what can be done to fix it?

Suggestion to use `command` to launch script at boot

Right now /usr/local/bin/wsl-iphandler.sh script runs every time when you open a new console. But really it only needed to be run at boot of the WSL2 VM.

You can use command setting in /etc/wsl.conf. Although it works only in Windows 11. Or you can create checks at the start of the script that will check if the settings already applied and exit.

WSL2 machine lost its static IP after shutdown

Hello,

With git commit 8ef8b3a - Fix spelling error in Readme.

After reboot, starting a PowerShell 7.1+ as a normal user:

PS> wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2

PS> Get-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -AddressFamily IPv4
Get-NetIPAddress: No matching MSFT_NetIPAddress objects found by CIM query for instances of the ROOT/StandardCimv2/MSFT_NetIPAddress class on the  CIM server: SELECT * FROM MSFT_NetIPAddress  WHERE ((InterfaceAlias LIKE 'vEthernet (WSL)')) AND ((AddressFamily = 2)). Verify query parameters and retry.

PS> Import-Module $Env:USERPROFILE\git\github.com\WSL-IpHandler

PS> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.50.1 -WslInstanceIpAddress 192.168.50.2

PS> Get-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -AddressFamily IPv4

IPAddress         : 192.168.50.1
InterfaceIndex    : 69
InterfaceAlias    : vEthernet (WSL)
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore

# WSL2 IP is correct, DNS server is incorrect
PS> wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2
PS> wsl hostname -I
192.168.50.2
PS> wsl cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 172.25.192.1

# Same after terminate
PS> wsl --terminate Ubuntu-20.04; wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2
PS> wsl hostname -I; wsl cat /etc/resolv.conf
192.168.50.2
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 172.25.192.1

# After shutdown, DNS server is now correct, but WSL2 lost its static IP
PS> wsl --shutdown; wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2
PS> wsl hostname -I; wsl cat /etc/resolv.conf
192.168.50.233
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 192.168.50.1

# No change after terminate
PS> wsl --terminate Ubuntu-20.04; wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped
PS> wsl hostname -I; wsl cat /etc/resolv.conf
192.168.50.233
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 192.168.50.1

# Yet a different WSL2 IP after shutdown
PS> wsl --shutdown; wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2
PS> wsl hostname -I; wsl cat /etc/resolv.conf
192.168.50.278
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 192.168.50.1

Both the DNS server and the WSL2 IP should be fixed after shutdown.

Best regards,
Olivier

Failed to install Wsl-IpHandler

Installation fails on Win11 via Terminal with:

Install-WslIpHandler -WslInstanceName "Ubuntu-22.04" -WslHostName ubuntu -GatewayIpAddress 192.168.31.1 -PrefixLength 25 -WslInstanceIpAddress 192.168.31.2 -DontModifyPsProfile -UseScheduledTaskOnUserLogOn
PowerShell installing Wsl-IpHandler to Ubuntu-22.04...
[sudo] password for admin:
bash: "C:UsersadminDocumentsPowerShellModulesWsl-IpHandlerScriptsBashinstall-wsl-iphandler.sh": No such file or directory
bash: line 1: ping -c1 windows 1>/dev/null && echo 1: No such file or directory
Test-WslInstallation on Ubuntu-22.04 Failed!
PowerShell finished installation of Wsl-IpHandler to Ubuntu-22.04 with Errors:
Pinging windows from WSL Instance: Ubuntu-22.04 failed:

Pinging ubuntu (WSL instance Ubuntu-22.04) from Windows failed.

Looks like escaping is broken somewhere as script trying to run script not via unix path

If I enter same command that fails in Debug, but in CMD:

wsl.exe -d Ubuntu-22.04 sudo -E env '"PATH=$PATH"' DEBUG=1 bash  $(wslpath "C:\Users\admin\Documents\PowerShell\Modules\Wsl-IpHandler\Scripts\Bash\install-wsl-iphandler.sh") "C:\Users\admin\Documents\PowerShell\Modules\Wsl-IpHandler\Scripts\Bash\wsl-iphandler.sh" /usr/local/bin "C:\Users\admin\Documents\PowerShell\Modules\Wsl-IpHandler\Scripts\Powershell\WSL-WinHostsEdit.ps1" /etc/wsl-iphandler.conf windows ubuntu 192.168.31.2

It looks like do not fail.

At the end of debug output:

bash: line 1: ping -c1 windows 1>/dev/null && echo 1: No such file or directory
DEBUG: Test-WslInstallation [1663]: $wslTest:
DEBUG: Test-WslInstallation [1673]: Starting WSL instance Ubuntu-22.04 for testing ping from Windows.
DEBUG: Test-WslInstallation [1681]: $windowsTest result: True
Test-WslInstallation on Ubuntu-22.04 Failed!
PowerShell finished installation of Wsl-IpHandler to Ubuntu-22.04 with Errors:
DEBUG: Install-WslIpHandler [294]: ScriptStackTrace: at Test-WslInstallation, C:\Users\admin\Documents\PowerShell\Modules\Wsl-IpHandler\Wsl-IpHandler.psm1: line 1695
at Install-WslIpHandler, C:\Users\admin\Documents\PowerShell\Modules\Wsl-IpHandler\Wsl-IpHandler.psm1: line 290
at <ScriptBlock>, <No file>: line 1
Pinging windows from WSL Instance: Ubuntu-22.04 failed:

issue with IpAddressToString

I get this error after i go through all of the steps and try to edit the interface.
Install-WslIpHandler -WslInstanceName Ubuntu -GatewayIpAddress 192.168.0.1 PowerShell installing Wsl-IpHandler to Ubuntu... Install-WslIpHandler: The property 'IPAddressToString'cannot be found on this object. Verify that the property exists.

Unable to find 'GenerateResolvConf' on instanceStatus object

When I am trying to run Install-WslIpHandler either in static or dynamic mode, it is throwing this error.

Test-EtcWslConfAndPrompt: The property 'GenerateResolvConf' cannot be found on this object. Verify that the property exists.

If I perform these steps,

$WslInstanceName = 'Ubuntu-20.04'
$instanceStatus = Get-WslInstanceStatus -WslInstanceName $WslInstanceName -WslConf
$instanceStatus

the following is the output:

PS C:\Users\ganapati.b> $instanceStatus
There is no distribution with the supplied name.

WslInstanceName    : Ubuntu-20.04
StaticIp           :
DynamicIp          :
WslHostName        :
WindowsHostName    :
ModuleScript       :
ModuleSudoers      :
GenerateResolvConf : True
AutomountEnabled   : True
InteropEnabled     : True
AppendWindowsPath  : True

Debug/Verbose logs

PowerShell installing Wsl-IpHandler to Ubuntu-20.04...
DEBUG: Install-WslIpHandler [204]: $PSBoundParameters: -WslInstanceName: Ubuntu-20.04 -GatewayIpAddress: 172.42.24.1 -WslInstanceIpAddress: 172.42.24.242 -AutoFixWslConfig: True -Debug: True -Verbose: True
DEBUG: Get-PrivateData [81]: Returning Cached WslPrivateData.Count: 5
DEBUG: Get-PrivateData [81]: Returning Cached WslPrivateData.Count: 5
DEBUG: Get-WslConfigValue [216]: $SectionName = 'wsl2'
DEBUG: Get-WslConfigValue [217]: $KeyName = 'swap'
DEBUG: Get-WslConfigValue [218]: $DefaultValue = ''
DEBUG: Get-WslConfigSection [125]: $SectionName = 'wsl2'
DEBUG: Get-WslConfig [53]: Returning Cached Config...
DEBUG: Get-WslConfig [53]: Returning Cached Config...
DEBUG: Test-WslConfigSectionExists [105]: $SectionName = 'wsl2'
DEBUG: Test-WslConfigSectionExists [108]: Section 'wsl2' Exists!
DEBUG: Get-WslConfigValue [223]: Section 'wsl2' has no key: 'swap'!
DEBUG: Get-WslConfigValue [226]: Returning $DefaultValue: '' without modifying the section: 'wsl2'
DEBUG: Get-WslStatus [1822]: $swapSize: ''
DEBUG: Get-PrivateData [81]: Returning Cached WslPrivateData.Count: 5
DEBUG: Get-PrivateData [81]: Returning Cached WslPrivateData.Count: 5
DEBUG: Get-WslConfigValue [216]: $SectionName = 'wsl2'
DEBUG: Get-WslConfigValue [217]: $KeyName = 'swapFile'
DEBUG: Get-WslConfigValue [218]: $DefaultValue = ''
DEBUG: Get-WslConfigSection [125]: $SectionName = 'wsl2'
DEBUG: Get-WslConfig [53]: Returning Cached Config...
DEBUG: Get-WslConfig [53]: Returning Cached Config...
DEBUG: Test-WslConfigSectionExists [105]: $SectionName = 'wsl2'
DEBUG: Test-WslConfigSectionExists [108]: Section 'wsl2' Exists!
DEBUG: Get-WslConfigValue [223]: Section 'wsl2' has no key: 'swapFile'!
DEBUG: Get-WslConfigValue [226]: Returning $DefaultValue: '' without modifying the section: 'wsl2'
DEBUG: Get-WslStatus [1832]: $swapFile: '%USERPROFILE%\AppData\Local\Temp\swap.vhdx'
DEBUG: Get-PrivateData [81]: Returning Cached WslPrivateData.Count: 5
DEBUG: Get-PrivateData [81]: Returning Cached WslPrivateData.Count: 5
DEBUG: Get-WslConfigValue [216]: $SectionName = 'wsl2'
DEBUG: Get-WslConfigValue [217]: $KeyName = 'swapFile'
DEBUG: Get-WslConfigValue [218]: $DefaultValue = ''
DEBUG: Get-WslConfigSection [125]: $SectionName = 'wsl2'
DEBUG: Get-WslConfig [53]: Returning Cached Config...
DEBUG: Get-WslConfig [53]: Returning Cached Config...
DEBUG: Test-WslConfigSectionExists [105]: $SectionName = 'wsl2'
DEBUG: Test-WslConfigSectionExists [108]: Section 'wsl2' Exists!
DEBUG: Get-WslConfigValue [223]: Section 'wsl2' has no key: 'swapFile'!
DEBUG: Get-WslConfigValue [226]: Returning $DefaultValue: '' without modifying the section: 'wsl2'
DEBUG: Get-WslStatus [1843]: $swapFileExpanded: 'C:\Users\hradmin\AppData\Local\Temp\swap.vhdx'
VERBOSE: ConvertFrom-IniContent: Function started
DEBUG: ConvertFrom-IniContent [77]: PsBoundParameters:
DEBUG: ConvertFrom-IniContent [83]: commentRegex is: ^(?<comment>\s*[;#].*)$
DEBUG: ConvertFrom-IniContent [84]: sectionRegex is: ^\s*\[(?<section>.+)\]\s*$
DEBUG: ConvertFrom-IniContent [85]: keyRegex is: ^\s*(?<name>.+?)\s*=\s*(?<quote>['"]?)(?<value>.*)\2\s*$
VERBOSE: ConvertFrom-IniContent: Started Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Finished Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Started Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Finished Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Started Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Finished Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Started Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Finished Processing 1 Lines of Content.
VERBOSE: ConvertFrom-IniContent: Function ended
DEBUG: Get-WslInstanceStatus [1979]: wslConf:

Test-EtcWslConfAndPrompt: The property 'GenerateResolvConf' cannot be found on this object. Verify that the property exists.

The part There is no distribution with the supplied name. is confusing to me. Few things that might be of interest/importance:

  • I am running this command in Admin mode. It is not possible to run them in normal user mode as that is disabled org wide.
  • Once I was able to realize that WSL installed in normal user mode is not visible in Admin mode, I tried to install Ubuntu in Admin mode as well but couldn't get any distributions listed under wsl.exe --list

Dynamic mode requires gateway parameter

I just download the module with the web-installer and git, but I got some errors trying to install it.

The documentation specifies for the dynamic mode I can use the command:
Install-WslIpHandler Ubuntu

But it gives an error requiring extra parameters:
PS C:\Users\default\Documents\PowerShell\Modules\Wsl-IpHandler> Install-WslIpHandler Ubuntu-20.04 PowerShell installing Wsl-IpHandler to Ubuntu-20.04... PowerShell finished installation of Wsl-IpHandler to Ubuntu-20.04 with Errors: Gateway IP Address is not specified neither as parameter nor in .wslconfig. WSL Hyper-V Network Adapter cannot be setup without Gateway IP Address!

Adding the required parameter I got a timeout:
PS C:\Users\default\Documents\PowerShell\Modules\Wsl-IpHandler> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.188.1 PowerShell installing Wsl-IpHandler to Ubuntu-20.04... Set-WslNetworkAdapter: vEthernet (WSL) Network Connection Setup did not succeed after [30] seconds. Try increasing timeout with '-Timeout' parameter.

And, If I try to increase the timeout value that parameter does not exist:
PS C:\Users\default\Documents\PowerShell\Modules\Wsl-IpHandler> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.188.1 -Timeout 300 Install-WslIpHandler: A parameter cannot be found that matches parameter name 'Timeout'.

Uninstall-Package: No match was found for the specified search criteria and module names 'Wsl-IpHandler'.

Hello,

With git commit 8ef8b3a - Fix spelling error in Readme.

After reboot, starting a PowerShell 7.1+ as a normal user:

The command Uninstall-Module Wsl-IpHandler fails systematically.

PS> Import-Module $Env:USERPROFILE\git\github.com\WSL-IpHandler

PS> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.50.1 -WslInstanceIpAddress 192.168.50.2
PowerShell Installing WSL-IpHandler to Ubuntu-20.04...
Bash Installing WSL-IpHandler...
Bash Installed wsl-iphandler!
PowerShell Successfully Installed WSL-IpHandler to Ubuntu-20.04.

PS> Uninstall-WslIpHandler -WslInstanceName Ubuntu-20.04
PowerShell Uninstalling WSL-IpHandler from Ubuntu-20.04...
Bash Uninstalling WSL-IpHandler...
Bash Uninstalled WSL-IpHandler.
PowerShell Successfully Uninstalled WSL-IpHandler from Ubuntu-20.04.

PS> Uninstall-Module Wsl-IpHandler
Uninstall-Package: C:\program files\windowsapps\microsoft.powershell_7.1.5.0_x64__8wekyb3d8bbwe\Modules\PowerShellGet\PSModule.psm1:12733
 Line |
12733 |$null = PackageManagement\Uninstall-Package @PSBoundParameters
      |                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      | No match was found for the specified search criteria and module names 'Wsl-IpHandler'.

Best regards,
Olivier

IPAddress not updated in NetAdpater if running Install-WslIpHandler with -Verbose -Debug

Hello,

With git commit 8ef8b3a - Fix spelling error in Readme.

After reboot, starting a PowerShell 7.1+ as a normal user:

PS> wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2

PS> Get-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -AddressFamily IPv4
Get-NetIPAddress: No matching MSFT_NetIPAddress objects found by CIM query for instances of the ROOT/StandardCimv2/MSFT_NetIPAddress class on the  CIM server: SELECT * FROM MSFT_NetIPAddress  WHERE ((InterfaceAlias LIKE 'vEthernet (WSL)')) AND ((AddressFamily = 2)). Verify query parameters and retry.

PS> Import-Module $Env:USERPROFILE\git\github.com\WSL-IpHandler -Verbose
VERBOSE: Loading module from path 'C:\Users\crozier\git\github.com\WSL-IpHandler\WSL-IpHandler.psd1'.
VERBOSE: Importing function 'Install-WslIpHandler'.
VERBOSE: Importing function 'Invoke-WslStatic'.
VERBOSE: Importing function 'Remove-ProfileContent'.
VERBOSE: Importing function 'Remove-WslInstanceStaticIpAddress'.
VERBOSE: Importing function 'Remove-WslNetworkAdapter'.
VERBOSE: Importing function 'Remove-WslNetworkConfig'.
VERBOSE: Importing function 'Set-ProfileContent'.
VERBOSE: Importing function 'Set-WslInstanceStaticIpAddress'.
VERBOSE: Importing function 'Set-WslNetworkAdapter'.
VERBOSE: Importing function 'Set-WslNetworkConfig'.
VERBOSE: Importing function 'Test-WslInstallation'.
VERBOSE: Importing function 'Uninstall-WslIpHandler'.
VERBOSE: Importing function 'Update-WslIpHandlerModule'.

PS> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.50.1 -WslInstanceIpAddress 192.168.50.2 -Verbose -Debug
PowerShell Installing WSL-IpHandler to Ubuntu-20.04...
...
Bash Installed wsl-iphandler!
VERBOSE: Modifying Powershell Profile: C:\Users\crozier\Documents\PowerShell\profile.ps1 ...
DEBUG: Set-ProfileContent: ProfilePath: C:\Users\crozier\Documents\PowerShell\profile.ps1
DEBUG: Get-PrivateData: Returning Cached PrivateData:
Name                           Value
----                           -----
ProfileContent                 {# Start of WSL-IpHandler Section, Import-Module WSL-IpHandler -Force, Set-Alias wsl Invoke-WslStatic, # End of WSL-IpHandler Section}
ScriptLocations                {BashAutorun}
WslConfig                      {GatewayIpAddressKeyName, StaticIpAddressesSectionName, NetworkSectionName, DnsServersKeyName…}
ScriptNames                    {BashInstall, WinHostsEdit, BashUninstall, BashAutorun}


VERBOSE: Terminating running instances of Ubuntu-20.04 ...
VERBOSE: Testing Activation of WSL IP Handler on Ubuntu-20.04 ...
DEBUG: Get-PrivateData: Returning Cached PrivateData:
Name                           Value
----                           -----
ProfileContent                 {# Start of WSL-IpHandler Section, Import-Module WSL-IpHandler -Force, Set-Alias wsl Invoke-WslStatic, # End of WSL-IpHandler Section}
ScriptLocations                {BashAutorun}
WslConfig                      {GatewayIpAddressKeyName, StaticIpAddressesSectionName, NetworkSectionName, DnsServersKeyName…}
ScriptNames                    {BashInstall, WinHostsEdit, BashUninstall, BashAutorun}


DEBUG: Test-WslInstallation: Testing Ping from WSL instance Ubuntu-20.04: "ping -c1 windows"
VERBOSE: Test-WslInstallation: Test Succeeded!
VERBOSE: Finished Testing Activation of WSL IP Handler.
PowerShell Successfully Installed WSL-IpHandler to Ubuntu-20.04.

PS> Get-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -AddressFamily IPv4

IPAddress         : 192.168.224.1
InterfaceIndex    : 67
InterfaceAlias    : vEthernet (WSL)
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 20
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore


PS> wsl hostname -I
192.168.50.2

PS> wsl cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 192.168.224.1

The Get-NetIPAddress command should return the IPAddress : 192.168.50.1.

See also issue #4 for the wrong nameserver in /etc/resolv.conf.

Best regards,
Olivier

Uninstall-WSLIpHandler error: Cannot convert value "ScriptNames" to type "System.Int32".

> Uninstall-WSLIpHandler -WslInstanceName Ubuntu-20.04  -Verbose -Debug
PowerShell Uninstalling WSL-IpHandler from Ubuntu-20.04...
DEBUG: Get-PrivateData: PrivateData is null or -Force parameter has been set!
DEBUG: Get-PrivateData: Using $MyInvocation.MyCommand.Module: WSL-IpHandler
DEBUG: Get-PrivateData: Cloned PrivateData - Count: 5
DEBUG: Get-PrivateData: PsData removed from PrivateData
Get-ScriptName: C:\Users\me\Documents\PowerShell\Modules\WSL-IpHandler\FunctionsPrivateData.ps1:68
Line |
  68 |      Join-Path $PSScriptRoot (Get-ScriptName $ScriptName) -Resolve
     |                               ~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot convert value "ScriptNames" to type "System.Int32". Error: "Input string was not in a correct
     | format."

Wsp-IpHandler vs WSP-IpHandler

It works, thank you!. But not before I used:
Import-Module WSL-IpHandler instead of:
Import-Module Wsl-IpHandler (note the capitals).

(Also I was running Powershell as Admin when it worked, but I didn't test non-admin and capitals.)

When it didn't work (for people googling) I received the following errors:

PowerShell installing WSL-IpHandler to Ubuntu...
[sudo] password for me:
Bash Installing WSL-IpHandler...
Bash Installed WSL-IpHandler!
PowerShell finished installation of WSL-IpHandler to Ubuntu with Errors:
Pinging windows from Ubuntu failed:
PING windows (<old ip>) 56(84) bytes of data.
From Ubuntu (172.16.0.2) icmp_seq=1 Destination Host Unreachable

--- windows ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms

and

> Install-WslIpHandler Ubuntu -Verbose -Debug
PowerShell installing WSL-IpHandler to Ubuntu...
DEBUG: Get-PrivateData: PrivateData is null or -Force parameter has been set!
DEBUG: Get-PrivateData: Using $MyInvocation.MyCommand.Module: WSL-IpHandler
Get-PrivateData: C:\Users\me\Documents\PowerShell\Modules\Wsl-IpHandler\FunctionsPrivateData.ps1:49
Line |
  49 |      $local:ScriptNames = (Get-PrivateData $ModuleInfo)['ScriptNames']
     |                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Value cannot be null. (Parameter 'ModuleInfo in Get-PrivateData does not have PrivateData!')

So I suggest a find/replace to consistently use the case-sensitive spelling of the module name everywhere including docs.

WslInstanceName argument completer fails when OutputEncoding is not UTF-8

Hello,

i installed the module according to the manual and when trying to set it up with the default commands i get the error "Install-WslIpHandler: Cannot validate argument on parameter 'WslInstanceName'. Valid values generator return a null value."

image
I tried different WslInstanceNames, both "fedoraremix" (which worked with wsl itself) and "fedoraremix (Standard)". When ommiting the parameter the tool asks me as a prompt, but i get the same error message.
I also tried it with quotes and without

Any ideas on this? Thanks

Edit: Pretty sure it has something to do with this output:
image
There are blank lines in there, depending on where i put the ConvertFrom-UTF16toUTF8 i get a different error (something encoding related)

DNS nameserver is not updated in /etc/resolv.conf with WSL gateway IP

Hello,

With git commit 8ef8b3a - Fix spelling error in Readme.

After reboot, starting a PowerShell 7.1+ as a normal user:

PS> wsl --list --verbose
  NAME            STATE           VERSION
* Ubuntu-20.04    Stopped         2

PS> Get-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -AddressFamily IPv4
Get-NetIPAddress: No matching MSFT_NetIPAddress objects found by CIM query for instances of the ROOT/StandardCimv2/MSFT_NetIPAddress class on the  CIM server: SELECT * FROM MSFT_NetIPAddress  WHERE ((InterfaceAlias LIKE 'vEthernet (WSL)')) AND ((AddressFamily = 2)). Verify query parameters and retry.

PS> Import-Module $Env:USERPROFILE\git\github.com\WSL-IpHandler
PS> Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 192.168.50.1 -WslInstanceIpAddress 192.168.50.2
PowerShell Installing WSL-IpHandler to Ubuntu-20.04...
Bash Installing WSL-IpHandler...
Bash Installed wsl-iphandler!
PowerShell Successfully Installed WSL-IpHandler to Ubuntu-20.04.

PS> Get-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -AddressFamily IPv4

IPAddress         : 192.168.50.1
InterfaceIndex    : 69
InterfaceAlias    : vEthernet (WSL)
AddressFamily     : IPv4
Type              : Unicast
PrefixLength      : 24
PrefixOrigin      : Manual
SuffixOrigin      : Manual
AddressState      : Preferred
ValidLifetime     : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource      : False
PolicyStore       : ActiveStore


PS> wsl hostname -I
192.168.50.2

PS> wsl cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 172.29.64.1

The file /etc/resolv.conf should contain nameserver 192.168.50.1.

Best regards,
Olivier

Bash scripts cannot be found when module is installed on a network share (i.e. Error: install-wsl-iphandler.sh: No such file or directory)

Sorry for posting all these issues. But running the new version 0.11.5 I once again get an error that the install-wsl-iphandler.sh is not found. Have verified that it exists in the correct folder..

Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 172.26.0.1 -WslInstanceIpAddress 172.26.0.2 -UseScheduledTaskOnUserLogOn -DontModifyPsProfile -Verbose
PowerShell installing WSL-IpHandler to Ubuntu-20.04...
VERBOSE: Hyper-V VM Adapter 'WSL' already exists.
VERBOSE: Hyper-V VM Adapter 'WSL' already has required Gateway: '172.26.0.1' and PrefixLength: '24'!
VERBOSE: Setting Static IP Address: 172.26.0.2 for Ubuntu-20.04.
VERBOSE: Registering WSL-IpHandler scheduled task...
VERBOSE: Scheduled Task to register: \WSL-IpHandler\WSL-IpHandlerTask
VERBOSE: Task command: 'C:\Program Files\PowerShell\7\pwsh.exe'
VERBOSE: Task command arguments: "-NoLogo -NoProfile -NonInteractive -WindowStyle Hidden -Command `"Import-Module '\\<SERVER>\<USER>\PowerShell\Modules\Wsl-IpHandler\WSL-IpHandler.psd1'; Set-WslNetworkAdapter -Wait -Timeout:30 -Toast -Duration:5`""
VERBOSE: Running Bash WSL Install script Microsoft.PowerShell.Core\FileSystem::\\<SERVER>\<USER>\PowerShell\Modules\Wsl-IpHandler\Scripts\Bash\install-wsl-iphandler.sh
[sudo] password for <USER>:
bash: Microsoft.PowerShell.Core/FileSystem::/<SERVER>/<USER>/PowerShell/Modules/Wsl-IpHandler/Scripts/Bash/install-wsl-iphandler.sh: No such file or directory

VERBOSE: Installed Bash scripts.
VERBOSE: Terminating running instances of Ubuntu-20.04 ...
VERBOSE: Testing Activation of WSL IP Handler on Ubuntu-20.04 ...
VERBOSE: Testing Ping from WSL instance Ubuntu-20.04: "ping -c1 windows 2>&1" ...
VERBOSE: Hyper-V VM Adapter 'WSL' already exists.
VERBOSE: Hyper-V VM Adapter 'WSL' already has required Gateway: '172.26.0.1' and PrefixLength: '24'!
VERBOSE: vEthernet (WSL) Network Connection Setup succeeded after [0] seconds.
VERBOSE: Ping from WSL Instance Ubuntu-20.04 failed:
ping: windows: Temporary failure in name resolution
VERBOSE: Testing Ping from Windows to WSL instance Ubuntu-20.04 ...
VERBOSE: Ping from Windows to WSL instance Ubuntu-20.04 failed:
Ping request could not find host Ubuntu-20.04. Please check the name and try again.
VERBOSE: Test-WslInstallation on Ubuntu-20.04 Failed!
PowerShell finished installation of WSL-IpHandler to Ubuntu-20.04 with Errors:
Pinging windows from Ubuntu-20.04 failed:
ping: windows: Temporary failure in name resolution

Changing /etc/wsl.conf file breaks WSL configuration

Hello. Thanks for this utility, it's really helpful.

I noticed a bug, that if you put any configuration in /etc/wsl.conf after this lines:

static_ip = 192.168.50.2
wsl_host = ubuntu
windows_host = windows

It won't be applied. So you need to make sure to put any other configuration above this lines. Maybe you could consider using any other file for configuration?

Cannot validate argument on parameter 'WslInstanceName'

When I follow the Module Activation section in README to activate in static mode, I got this error.
My command:

Install-WslIpHandler -WslInstanceName Ubuntu-20.04 -GatewayIpAddress 172.16.0.1

And the output:

Install-WslIpHandler: Cannot validate argument on parameter 'WslInstanceName'. Valid values generator return a null value.

image

Would you mind help me out there?
Thanks!

Property GenerateResolvConf cannot be found

When running the Install-WslIpHandler I get an error like so:

image

Not sure what i've done wrong but I followed the setup steps.

Here is the instances /etc/wsl.conf:

[boot]
systemd=true

[interop]
enabled = true
appendWindowsPath = true

[automount]
enabled = true

[network]
generateResolvConf = true

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.