Eric
Eric

Reputation: 2275

How do I match on wsl output in powershell?

I want to see if I'm running a particular wsl distribution (Windows 10 Home, WSL 2):

PS C:\Users\User> wsl --list --running
Windows Subsystem for Linux Distributions:
Ubuntu (Default)
MyDistro
PS C:\Users\User> wsl --list --running | Select-String -Pattern "MyDistro"
PS C:\Users\User>

No output. I used Get-Member to see that the output is a string; if I run it through something like | Out-String -stream it makes no difference.

I can get a match with Select-String . or Select-String .* but it matches everything, which isn't helpful.

Yes, I want to see if there's a running distro with a particular name. Is there a better way to do that in PowerShell?

Upvotes: 3

Views: 1287

Answers (2)

mklement0
mklement0

Reputation: 440412

Inexplicably, wsl --list --running produces UTF-16LE-encoded ("Unicode"-encoded) output by default instead of respecting the console's active code page, which defaults to the legacy system locale's OEM code page.


Update: As noted in Vimes' answer, v0.64 and above of wsl.exe (verify via the first line output by wsl.exe --version) now support setting the WSL_UTF8 environment variable to 1 to make wsl.exe output UTF-8-encoded output:

$env:WSL_UTF8 = 1
wsl --list --running | Select-String -Pattern MyDistro

This works, as long as your distro names comprise ASCII-range characters only (which seems likely), given that UTF-8 is a superset of ASCII, just like the OEM code pages are; if not, i.e. in the (unlikely) event that your distros contain non-ASCII-range characters (e.g. accented characters such as é):

  • If you happen to have configured your system to use UTF-8 system-wide, (in which case both the OEM and the ANSI code pages are UTF-8 - see this answer), the above solution works as-is.

  • Otherwise, use the proper workaround below or - with $env:WSL_UTF8 = 1 in effect - use the solution in this answer.


Without use of $env:WSL_UTF8:

A quick-and-dirty workaround - which assumes that all running distros are described only with ASCII-range characters (which seems likely) - is to use the following:

(wsl --list --running) -replace "`0" | Select-String -Pattern MyDistro

A proper workaround that supports all Unicode characters requires more effort:

$prev = [Console]::OutputEncoding; [Console]::OutputEncoding = [System.Text.Encoding]::Unicode
wsl --list --running | Select-String -Pattern MyDistro
[Console]::OutputEncoding = $prev

Upvotes: 13

Vimes
Vimes

Reputation: 11967

I just found that $env:WSL_UTF8=1 makes wsl.exe output UTF8. Select-String and More seem to work now!

(Prevoius answer: If you don't need regex then Select-String -simplematch seems to work.)

Upvotes: 2

Related Questions