wsl

install

  • hyper-v

    > Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
  • wsl

    > wsl --install
    Installing: Virtual Machine Platform
    Virtual Machine Platform has been installed.
    Installing: Windows Subsystem for Linux
    Windows Subsystem for Linux has been installed.
    Installing: Windows Subsystem for Linux
    Windows Subsystem for Linux has been installed.
    Installing: Ubuntu
    Ubuntu has been installed.
    The requested operation is successful. Changes will not be effective until the system is rebooted.
    • more

      > wsl --list --online
      
      # or
      > wsl --install -d <DistroName>
  • import tar.gz

    [!NOTE|label:references:]

    > curl -fsSL -O https://cloud-images.ubuntu.com/releases/focal/release/ubuntu-20.04-server-cloudimg-amd64-wsl.rootfs.tar.gz
    > wsl.exe --import
  • appx packages

    [!NOTE|label:download]

    > curl -fsSL -O https://wslstorestorage.blob.core.windows.net/wslblob/Ubuntu2204-221101.AppxBundle
    > Add-AppxPackage -Path /path/to/Ubuntu2204-221101.AppxBundle
  • reset

    [!NOTE|label:references:]

    > wsl --unregister <DistributionName>
    
    # or
    > wslconfig /unregister <DistributionName>
  • Microsoft-Windows-Subsystem-Linux

    > dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
    
    Deployment Image Servicing and Management tool
    Version: 10.0.19041.844
    
    Image Version: 10.0.19044.2604
    
    Enabling feature(s)
    [==========================100.0%==========================]
    The operation completed successfully.
    • or

      > Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
  • VirtualMachinePlatform

    > dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
    
    Deployment Image Servicing and Management tool
    Version: 10.0.19041.844
    
    Image Version: 10.0.19044.2604
    
    Enabling feature(s)
    [==========================100.0%==========================]
    The operation completed successfully.
  • set version to 2

    > wsl --set-default-version 2
    This application requires the Windows Subsystem for Linux Optional Component.
    The system may need to be restarted so the changes can take effect.

upgrade

[!NOTE|label:references:]

> Get-AppxPackage |? { $_.Name -like "*WindowsSubsystemforLinux*" }
Name              : MicrosoftCorporationII.WindowsSubsystemForLinux
Publisher         : CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
Architecture      : X64
ResourceId        :
Version           : 2.0.9.0
PackageFullName   : MicrosoftCorporationII.WindowsSubsystemForLinux_2.0.9.0_x64__8wekyb3d8bbwe
InstallLocation   : C:\Program Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_2.0.9.0_x64__8wekyb3d8bbwe
IsFramework       : False
PackageFamilyName : MicrosoftCorporationII.WindowsSubsystemForLinux_8wekyb3d8bbwe
PublisherId       : 8wekyb3d8bbwe
IsResourcePackage : False
IsBundle          : False
IsDevelopmentMode : False
NonRemovable      : False
IsPartiallyStaged : False
SignatureKind     : Store
Status            : Ok

> wsl --update
Checking for updates.
Updating Windows Subsystem for Linux to version: 2.0.14.

> Get-AppxPackage |? { $_.Name -like "*WindowsSubsystemforLinux*" }
Name              : MicrosoftCorporationII.WindowsSubsystemForLinux
Publisher         : CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
Architecture      : X64
ResourceId        :
Version           : 2.0.14.0
PackageFullName   : MicrosoftCorporationII.WindowsSubsystemForLinux_2.0.14.0_x64__8wekyb3d8bbwe
InstallLocation   : C:\Program
                    Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_2.0.14.0_x64__8wekyb3d8bbwe
IsFramework       : False
PackageFamilyName : MicrosoftCorporationII.WindowsSubsystemForLinux_8wekyb3d8bbwe
PublisherId       : 8wekyb3d8bbwe
IsResourcePackage : False
IsBundle          : False
IsDevelopmentMode : False
NonRemovable      : False
IsPartiallyStaged : False
SignatureKind     : Developer
Status            : Ok
  • update to pre-release version

    > wsl --update --pre-release
    Checking for updates.
    Updating Windows Subsystem for Linux to version: 2.1.3.
    
    > Get-AppxPackage |? { $_.Name -like "*WindowsSubsystemforLinux*" }
    Name              : MicrosoftCorporationII.WindowsSubsystemForLinux
    Publisher         : CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
    Architecture      : X64
    ResourceId        :
    Version           : 2.0.14.0
    PackageFullName   : MicrosoftCorporationII.WindowsSubsystemForLinux_2.0.14.0_x64__8wekyb3d8bbwe
    InstallLocation   : C:\Program
                        Files\WindowsApps\MicrosoftCorporationII.WindowsSubsystemForLinux_2.0.14.0_x64__8wekyb3d8bbwe
    IsFramework       : False
    PackageFamilyName : MicrosoftCorporationII.WindowsSubsystemForLinux_8wekyb3d8bbwe
    PublisherId       : 8wekyb3d8bbwe
    IsResourcePackage : False
    IsBundle          : False
    IsDevelopmentMode : False
    NonRemovable      : False
    IsPartiallyStaged : False
    SignatureKind     : Developer
    Status            : Ok

start up WSL

  • download

    > cd d:\Linux
    > Invoke-WebRequest -Uri https://wsldownload.azureedge.net/Ubuntu_2004.2020.424.0_x64.appx -OutFile Ubuntu20.04.appx -UseBasicParsing
  • rename

    > Rename-Item .\Ubuntu20.04.appx Ubuntu.zip
    > Expand-Archive .\Ubuntu.zip -Verbose
    > cd .\Ubuntu\
    > .\ubuntu2004.exe

init

> Restart-Computer

check

  • windows feature

    • appwiz.cpl

    • windows features

      > Get-WindowsOptionalFeature -Online | Where-Object {$_.State -eq "Enabled"} | format-table
      
      FeatureName                                   State
      -----------                                   -----
      WCF-Services45                              Enabled
      WCF-TCP-PortSharing45                       Enabled
      MediaPlayback                               Enabled
      SmbDirect                                   Enabled
      MSRDC-Infrastructure                        Enabled
      MicrosoftWindowsPowerShellV2Root            Enabled
      MicrosoftWindowsPowerShellV2                Enabled
      NetFx4-AdvSrvs                              Enabled
      Printing-PrintToPDFServices-Features        Enabled
      Printing-XPSServices-Features               Enabled
      SearchEngine-Client-Package                 Enabled
      WorkFolders-Client                          Enabled
      Internet-Explorer-Optional-amd64            Enabled
      Windows-Defender-Default-Definitions        Enabled
      Printing-Foundation-Features                Enabled
      Printing-Foundation-InternetPrinting-Client Enabled
      Microsoft-Windows-Subsystem-Linux           Enabled
      VirtualMachinePlatform                      Enabled
      Microsoft-Hyper-V-All                       Enabled
      Microsoft-Hyper-V                           Enabled
      Microsoft-Hyper-V-Tools-All                 Enabled
      Microsoft-Hyper-V-Management-PowerShell     Enabled
      Microsoft-Hyper-V-Hypervisor                Enabled
      Microsoft-Hyper-V-Services                  Enabled
      Microsoft-Hyper-V-Management-Clients        Enabled

reinstall

uninstall

[!NOTE|label:references:]

  • destroy distros

    > wsl --unregister all
    
    # or
    > wsl --unregister Ubuntu-22.04
    > wsl --unregister Ubuntu
    ...
    
    # if wsl hung, execute following cmd first
    > taskkill /f /im wslservice.exe
  • uninstall in Settings > Apps > Installed apps

    • Ubuntu

    • Ubuntu-22.04.3 LTS

  • disable in Start Menu > Turn Windows Features on or off

    • Virtual Machine Platform

    • Windows Subsystem for Linux

    • or via

      > Disable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
      > Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
      # or
      > DISM /online /disable-feature /featurename:VirtualMachinePlatform /norestart
      > DISM /online /disable-feature /featurename:Microsoft-Windows-Subsystem-Linux /norestart
      
      # check status
      > Get-Service vmcompute
      Status   Name               DisplayName
      ------   ----               -----------
      Running  vmcompute          Hyper-V Host Compute Service
  • reboot

    > Restart-Computer
  • others:

    > Dism /online /cleanup-image /restorehealth
    > sfc /scannow

reinstall

> Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
> Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
> Restart-Computer
> wsl --install --distribution Ubuntu

cmds

[!NOTE|label:references:]

  • commands:

    • wsl --update

    • wsl --version

    • wsl --list --running

    • wsl --shutdown

    • wsl hostname -i

    • wsl -d ubuntu

      • wsl -d Debian -u root

status

  • check status

    > wsl --status
    > wsl --list --verbose
    
    > wsl --list --verbose
      NAME            STATE           VERSION
    * Ubuntu-22.04    Stopped         1
      Ubuntu          Running         2
  • set wsl version

    • set default version

      > wsl --set-default-version <Version>
      
      # i.e.:
      > wsl --set-default-version 2
    • set distros

      > wsl --set-version <distribution name> <versionNumber>
      
      # i.e.:
      > wsl --set-version Ubuntu 2

users

  • run as root

    > wsl --distribution <Distribution Name> --user <User Name>
    
    # i.e.:
    > wsl --distribution Ubuntu-22.04 --user root
  • config default user

    > <DistributionName> config --default-user <Username>
    
    # i.e.:
    > Ubuntu-22.04 config --default-user root

shutdown

  • shutdown and terminate

    > wsl --shutdown
    > wsl --terminate <Distribution Name>
  • unregister

    > wsl --unregister <DistributionName>

disk

  • export and import

    # export
    > wsl --export <Distribution Name> <FileName>
    # for wsl2 to .vhdx
    > wsl --export <Distribution Name> --vhd <FileName>
    
    # import
    > wsl --import <Distribution Name> <InstallLocation> <FileName> [ --version 1/2 ]
    # for wsl2
    > wsl --import <Distribution Name> <InstallLocation> --vhd <FileName> [ --version 1/2 ]
    
    # import a distribution
    > wsl --import-in-place <Distribution Name> <FileName>
  • mount

    > wsl --mount <DiskPath>
    
    # for wsl2
    > wsl --mount <DiskPath> --vhd
    > wsl --unmount <DiskPath>

debug

[!NOTE|label:references:]

  • dump log

    > Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/collect-wsl-logs.ps1" -OutFile collect-wsl-logs.ps1
    > Set-ExecutionPolicy Bypass -Scope Process -Force
    > .\collect-wsl-logs.ps1 -Dump
  • host info

    • powershell

      > echo $PSVersionTable
      Name                           Value
      ----                           -----
      PSVersion                      7.4.1
      PSEdition                      Core
      GitCommitId                    7.4.1
      OS                             Microsoft Windows 10.0.22621
      Platform                       Win32NT
      PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
      PSRemotingProtocolVersion      2.3
      SerializationVersion           1.1.0.1
      WSManStackVersion              3.0
    • host network

      > Get-Service -Name 'Host Network Service'
      Status   Name               DisplayName
      ------   ----               -----------
      Running  hns                Host Network Service
  • packages

    > winget --info

features

[!NOTE|label:list windows features:]

> Get-WindowsOptionalFeature -Online | Where-Object {$_.State -eq "Enabled"} | format-table
  • VirtualMachinePlatform

    # enable
    > Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
    # or
    > DISM /online /enable-feature /featurename:VirtualMachinePlatform /norestart
    
    # disable
    > Disable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform
    # or
    > DISM /online /disable-feature /featurename:VirtualMachinePlatform /norestart
  • Microsoft-Windows-Subsystem-Linux

    # enable
    > Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
    # or
    > DISM /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /norestart
    
    # disable
    > Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
    # or
    > DISM /online /disable-feature /featurename:Microsoft-Windows-Subsystem-Linux /norestart
  • hyper-v

    [!NOTE|label:references:]

    # enable
    > Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
    # or
    > DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V-All
    > DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V
    
    # disable
    > Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All
    # or
    > DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V
    > DISM /Online /Enable-Feature /All /FeatureName:Microsoft-Hyper-V-All
    # win10
    > Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-Hypervisor

services

  • Host Network Service

    > Get-Service -Name 'Host Network Service' | Restart-Service
  • wslservices

    # restart wslservice
    > net stop wslservice
    > net start wslservice
    
    # if wsl hung, execute following cmd first
    > taskkill /f /im wslservice.exe
  • winsock

    [!NOTE|label:references:]

    > netsh winsock reset
    
    # reset tcp/ip settings
    > netsh int ip reset

others

  • mount

    # /mnt/c
    $ cat /etc/wsl.conf
    [automount]
    root=/
    
    # mount usb ( i.e.: F: )
    $ sudo mkdir /mnt/f
    $ sudo mount -t drvfs H: /mnt/f
    
    # mount dvd ( i.e.: G )
    $ sudo mkdir /mnt/g
    $ sudo mount -t drvfs G: /mnt/g
  • wsl files stored

    [!NOTE|label:references:]

    > cd %USERPROFILE%\AppData\Local\Packages\[distro name]
    
    REM i.e.:
    > %LOCALAPPDATA%\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState\rootfs\home\pawelb.

q&a

Error: 0x80040326

  • issue

    Error: 0x80040326
    Error code: Wsl/Service/CreateInstance/0x80040326
  • solution

    # start powershell with administrator
    
    > wsl --update
    Checking for updates.
    Updating Windows Subsystem for Linux...
    > wsl --shutdown
    > wsl -d ubuntu
    To run a command as administrator (user "root"), use "sudo <command>".
    See "man sudo_root" for details.

Error 4294967295

[!NOTE|label:references:]

> netsh winsock reset

# disable
> DISM /online /disable-feature /featurename:VirtualMachinePlatform /norestart
> DISM /online /disable-feature /featurename:Microsoft-Windows-Subsystem-Linux /norestart

# restart
> Restart-Computer

# enable
> DISM /online /enable-feature /featurename:VirtualMachinePlatform /norestart
> DISM /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /norestart
  • check vmcompute

    > Get-Service vmcompute

run-detectors: unable to find an interpreter

[!INFO|label:references:]

# execute in wsl2
sudo update-binfmts --disable cli
  • more

    $ mount | grep binfmt_misc
    binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,relatime)

tip

> set "PATH=%ConEmuBaseDirShort%\wsl;%PATH%" & %ConEmuBaseDirShort%\conemu-cyg-64.exe --wsl -cur_console:pm:/mnt
  • enable windows programe in wsl

    $ cat /etc/wsl.conf
    [interop]
    enabled=false
  • append windows path

    • via regedit

      > REG ADD "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss" /v AppendNtPath /t REG_DWORD /d 0x00000000
    • via wsl.conf

      $ cat /etc/wsl.conf
      [interop]
      appendWindowsPath=false

isWsl or isUbuntu

[!TIP]

  • uname -r

    $ uname -r | grep -q "Microsoft"
  • /proc/sys/kernel/osrelease or /proc/version

    $ cat /proc/version
    Linux version 5.15.133.1-microsoft-standard-WSL2 (root@1c602f52c2e4) (gcc (GCC) 11.2.0, GNU ld (GNU Binutils) 2.37) #1 SMP Thu Oct 5 21:02:42 UTC 2023
    
    $ cat /proc/sys/kernel/osrelease
    5.15.133.1-microsoft-standard-WSL2

enable nvim clipboard

$ sudo apt install xclip
$ nvim
:checkhealth

enable vim clipboard

[!NOTE|label:references:]

# install wl-clipboard
$ sudo apt install wl-clipboard -y

$ sudo apt-get install vim-gtk
$ vim --version | grep clipboard
+clipboard         +keymap            +printer           +vertsplit
+eval              -mouse_jsbterm     -sun_workshop      +xterm_clipboard

# or
$ sudo add-apt-repository ppa:jonathonf/vim
$ sudo apt update
$ sudo apt install vim
  • vimrc

    • with wl-clipboard

      set clipboard=unnamed
      set clipboard=unnamedplus
    • without wl-clipboard

      set clipboard^=unnamed
      set clipboard^=unnamedplus

wsl.conf

[!NOTE|label:references:]

  • /etc/wsl.conf

    [boot]
    systemd=true
    
    [network]
    generateResolvConf = false
    
    [automount]
    enable = true
    mountFsTab = true
    options = "metadata,umask=22,fmask=11"
    
    [interop]
    enable = false
    appendWindowsPath = false
  • %USERPROFILE%\.wslconfig

    # Settings apply across all Linux distros running on WSL 2
    [wsl2]
    
    # Limits VM memory to use no more than 4 GB, this can be set as whole numbers using GB or MB
    memory=4GB
    
    # Sets the VM to use two virtual processors
    processors=4
    
    # Specify a custom Linux kernel to use with your installed distros. The default kernel used can be found at https://github.com/microsoft/WSL2-Linux-Kernel
    # kernel=C:\\temp\\myCustomKernel
    
    # Sets additional kernel parameters, in this case enabling older Linux base images such as Centos 6
    $ kernelCommandLine = vsyscall=emulate
    
    # Sets amount of swap storage space to 8GB, default is 25% of available RAM
    swap=4GB
    
    # Sets swapfile path location, default is %USERPROFILE%\AppData\Local\Temp\swap.vhdx
    swapfile=C:\\temp\\wsl-swap.vhdx
    
    # Disable page reporting so WSL retains all allocated memory claimed from Windows and releases none back when free
    pageReporting=false
    
    # Turn off default connection to bind WSL 2 localhost to Windows localhost
    localhostforwarding=true
    
    # Disables nested virtualization
    nestedVirtualization=false
    
    # Turns off output console showing contents of dmesg when opening a WSL 2 distro for debugging
    debugConsole=false
    
    # Enable experimental features
    [experimental]
    sparseVhd=true
  • restart wsl

    > wsl --list --running
    Windows Subsystem for Linux Distributions:
    Ubuntu (Default)
    Ubuntu-22.04
    
    > wsl --shutdown
  • setup default bash

    [!NOTE|label:references:]

    $ echo $SHELL
    /bin/bash
    # for current account
    $ chsh -s /usr/bin/bash
    # for root
    $ sudo chsh -s /usr/bin/bash
    $ exit
    
    # re-login
    $ echo $SHELL
    /usr/bin/bash
    # verify in /etc/passwd

[!NOTE|label:references:]

Get-ChildItem "HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss" -Recurse |
ForEach-Object {
    $distro_name = ($_ | Get-ItemProperty -Name DistributionName).DistributionName
    $distro_dir =  ($_ | Get-ItemProperty -Name BasePath).BasePath

    $distro_dir = Switch ($PSVersionTable.PSEdition) {
      "Core" {
        $distro_dir -replace '^\\\\\?\\',''
      }
      "Desktop" {
        if ($distro_dir.StartsWith('\\?\')) {
            $distro_dir
        } else {
            '\\?\' + $distro_dir
        }
      }
    }
    Write-Output "------------------------------"
    Write-Output "Distribution: $distro_name"
    Write-Output "Directory: $($distro_dir -replace '\\\\\?\\','')"
    $distro_size = "{0:N0} MB" -f ((Get-ChildItem -Recurse -LiteralPath "$distro_dir" | Measure-Object -Property Length -sum).sum / 1Mb)
    Write-Output "Size: $distro_size"
}

recover data

[!NOTE|label:references:]

Get-ChildItem HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss\ |
    ForEach-Object {
        (Get-ItemProperty $_.PSPATH) | Select-Object DistributionName,BasePath
    } | Format-List
  • mount

    $ mount -o ro /dev/sdx /mnt/wsl-rescue

release disk space

[!NOTE|label:references:]

> wsl --shutdown
> optimize-vhd -Path .\ext4.vhdx -Mode full
  • another

    > wsl --shutdown
    # open window Diskpart
    > diskpart
    > select vdisk file="C:\WSL-Distros\…\ext4.vhdx"
    > attach vdisk readonly
    > compact vdisk
    > detach vdisk
    > exit
  • or via .wslconf

    [wsl2]
    memory=6GB
    swap=6GB
    
    [experimental]
    autoMemoryReclaim=dropcache
    sparseVhd=true
  • or

    > wsl --manage Ubuntu --set-sparse false

Last updated