1

I'm trying to get the default WSL2 distribution name, into a variable, in PowerShell. But, for some reason, I'm struggling to use a regular expression against the output of wsl. I am not having this issue with other commands.

wsl --list returns 4 array elements:

$test = wsl --list | Where-Object { $_ -and $_ -ne ''}
echo $test
Windows Subsystem for Linux Distributions:
docker-desktop-data (Default)
docker-desktop
Ubuntu-20.04
echo $test.Count

Select-String Pattern Fails

I can pattern match a single letter:

echo $test | Select-String -Pattern 'e'

Windows Subsystem for Linux Distributions:
docker-desktop-data (Default)
docker-desktop

But pattern matching 2+ characters returns nothing

echo $test | Select-String -Pattern 'ef'

ForEach with Regular Expression

ForEach with a regular expression works with a single character

$test | ForEach-Object { if ($_ -like '*e*') {
        Write-Output $_
    }
}
Windows Subsystem for Linux Distributions:
docker-desktop-data (Default)
docker-desktop

But it doesn't work with multiple characters:

$test | ForEach-Object { if ($_ -like '*ef*') {
        Write-Output $_
    }
}

I'm assuming I'm missing something simple, but am currently at a loss. Thanks for looking!

James Dudley
  • 597
  • 1
  • 4
  • 14

1 Answers1

0

As pointed out by @Santiago Squarzon in Unable to use regular expression against WSL distribution list, this was an encoding issue fixed by adding [Console]::OutputEncoding = [System.Text.Encoding]::Unicode to the start of the script.

James Dudley
  • 597
  • 1
  • 4
  • 14