Сценарий

Сценарий

Сценарий

Чтобы автоматически установить и инициализировать WSL Ubuntu 18.04 с помощью powershell, я пытаюсь автоматически инициализировать/установить первое имя пользователя и пароль. Однако, когда я впервые запускаю wsl из команды powershell, powershell переходит в оболочку wsl, которая ждет, пока пользователь вручную введет пароль.

МВЭ

Я предпринял пять различных попыток передать имя пользователя, пароль (и еще раз пароль) в приглашение для ввода после инициализации wsl, которые содержатся в следующем MWE.

##############Required for MWE###################
# Enable wsl subsystems for linux (if powershell is ran in admin mode)
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

# Set Tls12 protocol to be able to download the wsl application
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# check to see if ubuntu1804 installation file exists and download the app otherwise
$fileToCheck = "Ubuntu1804.appx"
if (Test-Path $fileToCheck -PathType leaf) 
{"File does Exist"}
else
{Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1804 -OutFile Ubuntu1804.appx -UseBasicParsing}

# Actually install the wsl ubuntu 18.04 app
Add-AppxPackage .\Ubuntu1804.appx
Write-Output "Installed the ubuntu18.04"

# backup installation command if the first command did not function properly
invoke-expression -Command "Add-AppxPackage .\Ubuntu1804.appx"
Write-Output "Installed the ubuntu with backup attempt"


##############Actual attempts to initialize ubuntu without prompting for user input###################
Write-Host "Trying to initialize ubuntu"
# Attempt 0: makes it start installing the wsl but hangs prompting user name
#Write-Host "wsl whoami" 
# Attempt 0 conclusion: Starts installing the wsl but then waits on user input

# Attempt 0.1: So would like to pipe a "password | password | username | whoami" in there but that does not work.
#Write-Host "wsl 'somepassword | somepassword | someusername | whoami'"
#Write-Host "wsl somepassword | somepassword | someusername | whoami" 
# Attempt 0.1 conclusion: doesn't work, still dives into the wsl shell and waits on user input


# Attempt 1: does not make it start installing
#$output = bash -c "wsl whoami"
#$output = bash -c "wsl 'somepassword | somepassword | someusername | whoami'" 
# Attempt 1 conclusion: Does not work, requires a user input to start installing (e.g. arrow down) (and then waits on user input).


# Attempt 2: try to prevent the prompt for username by setting default user to root immediatly

# Attempt 2.1: First define path to the installed ubuntu1804.exe
$str1="/Users/"
$str2="/AppData/Local/Microsoft/WindowsApps/ubuntu1804"
$hdd_name=(Get-WmiObject Win32_OperatingSystem).SystemDrive
$username=$env:UserName
[String] $ubuntu1804_path=$hdd_name+$str1+$username+$str2

# Attempt 2.2: Create command to set root as default user
$str1=" config --default-user root"
$set_user=$ubuntu1804_path+$str1

# Attempt 2.3: Create command to set root as default user and execute it
#invoke-expression -Command $set_user 
# Attempt 2.3 conclusion: Doesn't work still asks for username and waits on user input


# Attempt 3: passing a username, password, and password again as one is prompted at the startup
$strA = "test | test | root"
#$output = bash "-c" $strA
# Attempt 3 conclusion: Doesn't work, requires user input to go to the next line (e.g. arrow down)

# Attempt 4: let root be default username
$str1=" install --root"
$set_user=$ubuntu1804_path+$str1
# Attempt 4 conclusion: Doesn't work, requires user input to go to the next line (e.g. arrow down)
invoke-expression -Command $set_user 
# Attempt 4 conclusion: Pending.

Write-Host "Done with setup."

Ни одна из попыток 0,1,2 и 3 не увенчалась успехом в автоматической инициализации WSL Ubuntu 18.04 без вмешательства пользователя. Проблемы попыток описаны в выводах в комментариях. Все сводится к тому, что wsl после активации начинает установку/инициализацию, но затем ждет ввода пользователя в окне powershell, не передавая туда оставшуюся часть команды.

Вопрос:

Как выполнить автоматическую установку и инициализацию WSL Ubuntu 18.04 из PowerShell?

Предположения

Я заранее знаю имя пользователя и пароль в переменной в Powershell.

решение1

Вместо использования Add-AppxPackageдля установки пакета Appx используйте Expand-Archive cmdlet для его извлечения в папку. Затем выполните ubuntu.exeдля настройки остальной части. СмотритеWSL: Руководство по установке Windows Serverдля дальнейших идей.

решение2

Объяснение

Четвертая попытка, которая инициализирует wsl с пользователем root по умолчанию в качестве аргумента (неткоманда ubuntu1804 config --default-user root) сработала и не требует ввода какого-либо пароля.

Решение

Следующий код автоматически устанавливает WSL Ubuntu 18.04 из PowerShell:

##############Downloading and installing the app###################
# Enable wsl subsystems for linux (if powershell is ran in admin mode)
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux

# Set Tls12 protocol to be able to download the wsl application
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# check to see if ubuntu1804 installation file exists and download the app otherwise
$fileToCheck = "Ubuntu1804.appx"
if (Test-Path $fileToCheck -PathType leaf) 
{"File does Exist"}
else
{Invoke-WebRequest -Uri https://aka.ms/wsl-ubuntu-1804 -OutFile Ubuntu1804.appx -UseBasicParsing}

# Actually install the wsl ubuntu 18.04 app
Add-AppxPackage .\Ubuntu1804.appx
Write-Output "Installed the ubuntu18.04"

# backup installation command if the first command did not function properly
invoke-expression -Command "Add-AppxPackage .\Ubuntu1804.appx"
Write-Output "Installed the ubuntu with backup attempt"


##############Initializing the wsl ubuntu 18.04 app without requiring user input###################

# First define path to the installed ubuntu1804.exe
$str1="/Users/"
$str2="/AppData/Local/Microsoft/WindowsApps/ubuntu1804"
$hdd_name=(Get-WmiObject Win32_OperatingSystem).SystemDrive
$username=$env:UserName
[String] $ubuntu1804_path=$hdd_name+$str1+$username+$str2

# let root be default username
$str1=" install --root"
$set_user=$ubuntu1804_path+$str1
invoke-expression -Command $set_user 

Write-Host "Done with setup."

Связанный контент