我尝试在 PowerShell 脚本中通过用户选择来设置默认的 Linux 发行版,但找不到任何使用变量设置发行版的方法。使用手动命令或使用以下脚本中的硬编码字符串设置默认分布可以正常工作。
尝试过这个 PowerShell 脚本:
$wslList = (wsl --list --quiet)
$wslFilteredList = @()
# To get rid of empty lines in Out-GridView window:
foreach ($item in $wslList) {
if ("$item" -ne "") {
$wslFilteredList += $item
}
}
Write-Output "Choose Linux distribution from pop-up window."
$selectedItem = ($wslFilteredList | Out-GridView -Title "Registered Linux distributions:" -PassThru)
Write-Host "`nSetting selected '$selectedItem' as default Linux distribution."
wsl --set-default "$selectedItem"
Read-Host -Prompt "`nPress Enter to continue"
结果: 显示 wsl 用法/帮助或消息:“没有具有所提供名称的发行版。”
预计: 获取 wsl 默认分发集。
附加信息:
据我所知,你的问题与这个重复,尽管你后来表示在调用
$env:WSL_UTF8=1
之前已经设置了wsl.exe
,这确实是先决条件。
后者无法工作的唯一原因是发行版名称包含非 ASCII字符,因为 PowerShell 会误解它们。
为了也解释这一点,请使用以下内容:
# Ensure what wsl's distro-management commands output UTF-8
$env:WSL_UTF8=1
# Call such a command while ensuring that its output is
# interpreted as UTF-8.
& {
$prevEnc = [Console]::OutputEncoding]
[Console]::OutputEncoding] = [System.Text.UTF8Encoding]::new()
# Collect the names of all distros in an array.
$wslFilteredList = @(wsl --list --quiet)
[Console]::OutputEncoding] = $prevEnc
}
# Simulate Out-Grid -PassThru with selecting the *first* distro
$selectedItem = $wslFilteredList[0]
# This should now succeed, even with distro names that contain non-ASCII
# characters.
wsl --set-default $selectedItem