November 9, 2019

Enumerating registered WSL distributions

Consuming the WSL API requires developers to provide the name of a distribution to action on. For example, here's the definition for WslLaunchInteractive:

HRESULT WslLaunchInteractive(
  PCWSTR distributionName,
  PCWSTR command,
  BOOL   useCurrentWorkingDirectory,
  DWORD  *exitCode
);

Confusingly, Microsoft does not provide an API to retrieve a list of registered (i.e. installed) distribution names to pass into this function. When I confronted Microsoft about this omission, one engineer suggested I parse the output of wsl --list. Another deflected, noting "there is a non-zero cost for creating and maintaining an API" and that perhaps when "WSL becomes more of a platform, a more robust set of APIs would probably make sense". I'm still discussing this on GitHub. And Twitter.

In the meantime, you could utilize the private LxssUserSession COM class–thanks Biswapriyo. Or just read the backing data store directly. (You're going down that undocumented road anyway.) As of Windows 10, build 19013.1, installed distribution data lives in the Windows Registry, at HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Lxss.

At its root, the Lxss key contains a helpful DefaultDistribution REG_SZ value pointing to the distribution sub-key currently configured as the user's default distribution. Each sub-key represents a single installed distribution. And each sub-key contains a DistributionName REG_SZ value. That is the distribution name the WSL API expects.