Great thanks to RichMatheisen-8856's detailed analysis and suggestions, we've found a workaround with Windows task scheduler, Add-WindowsCapability and ubuntu2004.exe all worked this way. Here's what we did(all steps are run through WinRM / Servertribe's Attune, aka remotely unattended management):
- Clear "Users must enter a user name and password to use this computer" and reboot the computer, to make sure a session is logged on at the console, which is required for scheduled tasks with "Run only when user is logged on" option set(which is itself required to run Add-WindowsCapability successfully) $RegPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
$DefaultUsername = "{win10cred1.user}"
$DefaultPassword = "{win10cred1.password}"
Set-ItemProperty $RegPath "AutoAdminLogon" -Value "1" -type String
Set-ItemProperty $RegPath "DefaultUsername" -Value "$DefaultUsername" -type String
Set-ItemProperty $RegPath "DefaultPassword" -Value "$DefaultPassword" -type String - Create a onetime scheduled task, please see detailed script within the blueprint here . The key to the success of this task is "Run only when user is logged on" and "Run with highest privileges" options. # Run the task 15 seconds after task creation
$ts = New-TimeSpan -Seconds 15
$Trigger = New-ScheduledTaskTrigger -Once -At ((Get-date) + $ts) # Run only when user is logged on / Run with highest privileges
$principal = New-ScheduledTaskPrincipal -UserId "{win10cred1.user}" -RunLevel Highest
$Action= New-ScheduledTaskAction -Execute "powershell.exe" -Argument "Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0"
$setting = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "Add-WindowsCapability OpenSSH.Server" -Trigger $Trigger -Principal $principal -Action $Action -Settings $setting -Force
The result is that, when scheduled time's up, a window will appear in the console session running the specified command, avoid getting errors compared to run the command directly from WinRM.