I stumbled over an interesting little trick for using environment variables in both Powershell and WSL sessions. Windows has a special environment variable named
WSLENV that is the source of the magic. You set
WSLENV to a list of environment variable names separated by colons, and it will then take the values from Powershell and export them into a WSL session when it starts up. (It also works from WSL to Windows programs too)
For example, you can set the AWS CLI environment variables in Powershell, and have the same variables and values available in a WSL session. There are some special macros that help with defining file and directory paths to ensure they get formatted correctly for Windows or Linux.
Microsoft Dev Blogs has the best explanation that I’ve found so far, but I found the instructions to be a bit confusing. I couldn’t get the
setx commands in their example to work properly, but I was able to make it work by modifying the value of
$env:WSLENV in Powershell. Using my AWS example above, I set
WSLENV to the following:
>$env.WSLENV = "$env.WSLENV:AWS_ACCESS_KEY_ID:AWS_SECRET_ACCESS_KEY:AWS_REGION"
As long as those variables are defined in Powershell, they will be available in the next WSL session that I start. To make the value permanent, add your custom
WSLENV statement to your Powershell profile.