0

I am trying to write a function to detect my default WSL installation.

function Get-WslDefault {
   $installs = (wsl --list -v)
   foreach ($s in $installs) {
    if ($s.StartsWith("*")) {
        return $s.Split(' ')[1]
    }
   } 
   return ""
}

This works in PS 7.2, but in Windows Powershell 5.1 (which I have to support) the strings in $installs look like they have been incorrectly translated from UTF16 - there is an unexpected space between each character. e.g.

    N A M E                                       S T A T E                       V E R S I O N 

instead of

  NAME                   STATE           VERSION

I have tried every possible combination of $OutputEncoding and [Console]::OutputEncoding and [Console]::InputEncoding and nothing seems to fix the problem.

Has anyone come across this and is there a workaround?

  • And yet, it is likely an encoding issue, see this answer: [Displaying Unicode in Powershell](https://stackoverflow.com/a/49481797/1701026). Try: `$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding` – iRon Jul 27 '22 at 06:30
  • https://github.com/microsoft/WSL/issues/4607#issuecomment-717876058 – Daniel Jul 27 '22 at 06:33
  • Thanks Daniel. That was one combination of "messing about with output encoding" that I did not try! For some reason I thought I would need to set the encoding to Utf8, but of course setting it to Unicode makes more sense. – user3200739 Jul 27 '22 at 06:53
  • Thanks Ron. I found that link while I was searching and the suggestion did not work. Setting [Console]::OutputEncoding to Unicode does work! – user3200739 Jul 27 '22 at 06:55

0 Answers0