microsoft / WSL

Issues found on WSL
https://docs.microsoft.com/windows/wsl
MIT License
17.23k stars 808 forks source link

Unable to start WSL via Task Scheduler #8835

Closed tvwenger closed 1 year ago

tvwenger commented 1 year ago

Version

22000.978

WSL Version

Kernel Version

5.15.57.1

Distro Version

Ubuntu 22.04

Other Software

No response

Repro Steps

Create a powershell script with the following:

# start SSH server and other applications in Ubuntu
wsl -d Ubuntu-22.04 -u root service ssh start
Start-Sleep -s 5

# add port forwarding rule (from WSL to host) for port 4242
$wsl_ip = (wsl hostname -I).trim()
Write-Host "WSL Machine IP: ""$wsl_ip"""
netsh interface portproxy add v4tov4 listenport=4242 connectport=4242 connectaddress=$wsl_ip

Create a Task Scheduler task to run the powershell script on boot.

Restart the machine, or manually run the task.

Expected Behavior

Upon reboot or manually running the task, the WSL instance should start and the ssh daemon should be running. This worked in previous versions of WSL (on Windows 10).

Actual Behavior

Either on reboot or on manually executing the task, WSL does not start.

C:\Windows\system32>wsl --list --running
There are no running distributions.

If I manually run the following command via the command prompt, WSL and the ssh daemon start properly.

C:\Windows\system32>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File C:\Scripts\startwsl.ps1
 * Starting OpenBSD Secure Shell server sshd                                                                                                                      [ OK ]
Starting seafile daemon ...
Started: seafile daemon ...
WSL Machine IP: "172.21.82.221"

C:\Windows\system32>wsl --list --running
Windows Subsystem for Linux Distributions:
Ubuntu-22.04 (Default)

In summary, running the same powershell script to launch WSL works from the command prompt but does not work from the task scheduler.

Diagnostic Logs

No response

OneBlue commented 1 year ago

/logs

ghost commented 1 year ago

Hello! Could you please provide more logs to help us better diagnose your issue?

To collect WSL logs, download and execute collect-wsl-logs.ps1 in an administrative powershell prompt:

Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/collect-wsl-logs.ps1" -OutFile collect-wsl-logs.ps1
Set-ExecutionPolicy Bypass -Scope Process -Force
.\collect-wsl-logs.ps1

The scipt will output the path of the log file once done.

Once completed please upload the output files to this Github issue.

Click here for more info on logging

Thank you!

tvwenger commented 1 year ago

I have attached two logs. _powershell.zip when I ran my powershell script via the command line to start WSL (success), and _taskscheduler.zip when I ran the powershell script via the task scheduler (failure). WslLogs-2022-09-21_20-52-49_powershell.zip WslLogs-2022-09-21_20-54-39_taskscheduler.zip

cheng-chi commented 1 year ago

I have the same problem. This problem seems to be specific to the Microsoft Store version of wsl. If I uninstall the Microsoft Store WSL app, task schedule can properly start wsl. I tried the vbs trick mentioned here without success. This problem seems to be related to the "Unable to start wsl.exe from a Session 0 prompt which users can run into when trying to start WSL from an ssh session" limitation mentioned in the release blogpost.

tvwenger commented 1 year ago

I can confirm, as @cheng-chi said, that this issue is only apparent in the Microsoft Store version of WSL. I am able to start WSL via the Task Scheduler when I use the non-Microsoft Store version.

tvwenger commented 1 year ago

And since I'd like to use WSLg, I need the Microsoft Store version...

brettus78 commented 1 year ago

+1 I have this issue too. Same deal - was working before. Then upgraded Windows to 22H2 & was prompted by WSL to run some WSL Update command for WSL to do with store (sadly I can't recall the exact command or find it - it was something that appeared at the first opening of a WSL terminal post-Windows update) - now Task Scheduler won't run my command anymore. Before that - it worked. Even if I open Task Scheduler, select the task, & click 'Run' - nothing happens. Same as the above poster, it works when I run exactly the same command that I have in Task Scheduler, directly from UN-elevated CMD or UN-elevated Powershell. CMD_WslLogs-2022-10-08_10-52-39.zip Task_Scheduler_WslLogs-2022-10-08_10-50-45.zip image At time of posting this - it's 10:55AM AWST on 08 October 2022 - it shows the last run time (even though I've been clicking RUN) as two days ago (06 October 2022) - which is when I installed the new Windows update. image

cheng-chi commented 1 year ago

I think I have found a solution. According to this StackOverflow answer, we can escalate a process out of session 0 using psexec.exe.

  1. Download PsTools and extract PsExec.exe to a convenient location.
  2. Replace your command running wsl with C:\<your psexec install path>\PsExec.exe -i 1 <your original command>
brettus78 commented 1 year ago

If the workaround works, it will be very useful until MS can resolve the issue. I'll give it a test & report back. Many thanks

brettus78 commented 1 year ago

Sadly the workaround didn't work. Even deleted the task & recreated it from scratch using the workaround, no change. Must be something to do with the Windows update.

cheng-chi commented 1 year ago

@brettus78 I have created a GitHub repo for my solution of running wsl at startup. I have also installed the Windows 11 22H2 update so I think it shouldn't be the issue.

sikhness commented 1 year ago

I have the same issue. If I try to use the psexec64.exe -i 1 <command> workaround, I keep getting a poweshell.exe exited with error code 0 error.

brettus78 commented 1 year ago

Been flat out - will try the example in the GitHub repo you posted, ASAP. But might be a couple of days before I get a chance.

seanballais commented 1 year ago

Just happy to report that using psexec64.exe worked for me. I didn't need to port forward SSH though, so I didn't test that part.

@sikhness, I actually got the same message when I ran the psexec64.exe command in PowerShell. If my memory serves me correctly, WSL 2 should be running in the background by then.

Log for October 15, 2022: I just found that it didn't actually work, after shutting down my system when I went to bed and opening it again hours after I woke up. Tried Distrod, but to no avail. I'm ditching WSL 2 for the moment, until they support having one instance usable by all users.

brettus78 commented 1 year ago

I'll need to do further testing to isolate - but I recently received another Windows update (around features like tabs in File Explorer). As a test triggered by SeanBallais' comment above "having one instance usable by all users" - I thought I should try a Task Scheduler task that only runs when I'm logged in. I tried it & it works. Not sure if because I chose to only run once logged in - or if resolved by the Windows update. Suspect the former. At some point, I'll try again with running without having logged in & see if it works since the update, but for now, it's working, so it's a low priority for me. image

tvwenger commented 1 year ago

I can confirm that it works if you run the script with "only when user is logged on" and triggered at log on.

mousumih commented 1 year ago

I need to use "Run whether user is logged in or not" to start wsl2 from taskScheduler. Is this working for anyone? Also can confirm that this is not only related to wsl2 - tried starting notepad.exe and had the same issue

GlenC289 commented 1 year ago

The only thing I found that worked is to change the user on the task to the group "Users". The downside is that it opens a terminal on the screen. I can't seem to minimize it on execution for some reason. Strange how everyone has a different method that works.

hammadrauf commented 1 year ago

@GlenC289 solution worked for me on Windows 11. I am copying my Task Scheduler Script. Comments indicate how I setup the Task. -NoExit argument to pwsh was necessary. I have installed wsl2 Ubuntu and enabled SystemD.

Code from the Filename: start-wsl-forward-ports.ps1 follows.

# WSL Start and Port Forwarding Script
# Task Scheduler Setup:
#   Run as user: Users
#   Run with highest privileges
#   Triggers: Startup delay 30 seconds
#   Action: script: "C:\Program Files\PowerShell\7\pwsh.exe"
#         Arguments: -NoExit -WindowStyle hidden -ExecutionPolicy Bypass -File "C:\scripts\wsl2\start-wsl-forward-ports.ps1"
#           Start in: C:\scripts\wsl2\
#   Settings: (2 only) 1) Allow task to be run on demand, 2) if the running task does not end......
#
Get-Date | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
Echo "Start WSL and port forwarding..." | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
$wsl_ip = (C:\Windows\system32\wsl.exe -d "Ubuntu-22.04" --shell-type login hostname -I).split(" ")[0]
# Following line runs an infinite long running job, so that WSL does not time out and exit.
C:\Windows\system32\wsl.exe -d "Ubuntu-22.04" tail -n 1 -f /dev/null &
Echo "WSL Machine IP: ""$wsl_ip""" | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
# Put Your Ports Forwarding below and uncomment
#netsh interface portproxy add v4tov4 listenport=4505 connectport=32377 connectaddress=$wsl_ip
#netsh interface portproxy add v4tov4 listenport=4506 connectport=32378 connectaddress=$wsl_ip
#netsh interface portproxy add v4tov4 listenport=8092 connectport=32380 connectaddress=$wsl_ip
#Write-Host "Completed - Start WSL and port forwarding..."
Echo "Completed - Start WSL and port forwarding..." | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
GlenC289 commented 1 year ago

@hammadrauf Thanks, I appreciate you taking the time to post your solution. I finally decided to remove the Microsoft Store version (as reported by cheng-chi) above and it has been working normally for me so far. I will keep your post in mind though, just in case MS carries the problem over to the windows version.

adepierre commented 1 year ago

Just ran in the same issue with windows store version trying to start WSL at startup on W10 "whether user is logged in or not".

I need to use the Store version to have systemd, but can't manage to make it start automatically :/

My workaround at the moment is launching it manually everytime the machine restarts, which is not ideal.

tvwenger commented 1 year ago

@adepierre

I can confirm that it works if you run the script with "only when user is logged on" and triggered at log on.

adepierre commented 1 year ago

@adepierre

I can confirm that it works if you run the script with "only when user is logged on" and triggered at log on.

Yeah that's what I do. But you still need to manually log in at each restart of the machine

aki-k commented 1 year ago

The psexec trick seems to work but not with the -s option. I put pstools into C:\pstools and then in the task scheduler start

Program/script: C:\PSTools\psexec64.exe Add arguments: -i 0 C:\PSTools\psexec64.exe -i 1 C:\Windows\System32\wsl.exe -d Ubuntu-20.04

I added a 30 second delay to the task startup and WSL starts without me logging into the system. There's still something that makes it stop, probably logging into the system with the user that WSL is running on.

Edit: I needed to change the startup delay from 30 seconds to 1 minute because only vmcompute.exe did start. vmwp.exe and vmmemWSL had trouble starting.

Edit 2: There's a console window appearing on my main account desktop during login. When I logout, WSL running in the other user session is closed so this is not working after all.

wangyoucao577 commented 1 year ago

+1

My task scheduler breaks after I run wsl --update and reboot the system. Currently I have to use the startup workaround: create a shortcut in the C:\Users\<USER>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup to run the commands when login.

Waiting for Microsoft to solve the issue..

aki-k commented 1 year ago

I'm unable to start WSL on either Win10 Pro or Win11 Pro through Task Scheduler. Task Scheduler history shows that the task started successfully but just wslservice.exe is running when I run "tasklist | findstr /i "vm wsl".

Task Scheduler successfully completed task "\start wsl" , instance "{db255c35-7af5-4ba4-ac84-57996065ccb4}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 0.

My action for the task is C:\Users\username\Scripts\startwsl.cmd which content is:

@echo off

C:\Windows\System32\wscript.exe //B C:\Users\username\Scripts\startwsl.vbs

C:\Users\username\Scripts\startwsl.vbs content is:

set object = createobject("wscript.shell")
object.run "C:\Windows\System32\wsl.exe --distribution Ubuntu-20.04", 0

I installed WSL with the command "wsl --install --web-download --no-distribution" and then imported the backup of the VM filesystem with:

mkdir C:\Users\siroadmin\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows
wsl --import Ubuntu-20.04 C:\Users\siroadmin\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows d:\WSL\Ubuntu-20.04.tar

I added the Windows feature Windows Subsystem for Linux because the filesystem import wouldn't work without it.

I also changed the default username to match the username username defined for the Task Scheduler task.

I have systemd running inside WSL VM so it should keep running even though I'm not using it.

Could it be that I somehow installed the Microsoft Store version of WSL that is known not to work with the Task Scheduler and session 0? This is baffling as I'm sure I had it working in Win11 Pro already.

Edit: Here's the process list that should be running when WSL VM starts up correctly:

C:\>tasklist | findstr /i "vm wsl"
wslservice.exe                6004 Services                   0     24 216 K
wsl.exe                      12204 Console                    1     11 012 K
wsl.exe                      10288 Console                    1     10 372 K
wslhost.exe                  11508 Console                    1      9 216 K
vmcompute.exe                11784 Services                   0     11 980 K
vmwp.exe                     12016 Services                   0     25 028 K
vmmemWSL                     12976 Services                   0  1 144 888 K
wslhost.exe                   7348 Console                    1      7 572 K
wslhost.exe                  14096 Console                    1     10 840 K
wslhost.exe                  12944 Console                    1      9 140 K
wslhost.exe                  10248 Console                    1      9 020 K
thojo0 commented 1 year ago

Same problm here. cmd.exe is writing The system cannot access the file. to stderr, when I try to execute wsl with Task Scheduler via Script.

bavtan commented 1 year ago

any update on the fix ?

aki-k commented 1 year ago

I was able to make WSL start on boot by using a Windows service. This is done with the non-store version of WSL.

I changed these things:

1) remove local admin rights from the user (Windows_username) that is running the new service

2) add "Log on as a service" rights for the user (Windows_username) in secpol.msc Security Settings/Local Policies/User Rights Assignment

3) download NSSM (Non-Sucking Service Manager) from https://nssm.cc/

4) create a new Windows service with these instructions:

    "C:\Program Files\nssm\win64\nssm.exe" install startwsl

    Application:

    Path: C:\Windows\System32\cmd.exe
    Startup directory: C:\Windows\System32
    Arguments: /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

    Details:

    Display name: startwsl
    Startup type: Automatic (delayed start)

    Log on:

    [x] Windows_username [ ] allow service to interact with desktop
        password    password

    Dependencies: lxssmanager

    Exit actions:

    Throttling: Delay restart if application runs for less than 10000 ms

    Install service
bavtan commented 1 year ago

I was able to make WSL start on boot by using a Windows service. This is done with the non-store version of WSL.

I changed these things:

  1. remove local admin rights from the user (Windows_username) that is running the new service
  2. add "Log on as a service" rights for the user (Windows_username) in secpol.msc Security Settings/Local Policies/User Rights Assignment
  3. download NSSM (Non-Sucking Service Manager) from https://nssm.cc/
  4. create a new Windows service with these instructions:
    "C:\Program Files\nssm\win64\nssm.exe" install startwsl

    Application:

    Path: C:\Windows\System32\cmd.exe
    Startup directory: C:\Windows\System32
    Arguments: /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

    Details:

    Display name: startwsl
    Startup type: Automatic

    Log on:

    [x] Windows_username [ ] allow service to interact with desktop
        password    password

    Dependencies: lxssmanager

    Exit actions:

    Throttling: Delay restart if application runs for less than 10000 ms

    Install service

i think non-store version is just fine but to have systemd enabled folks like me started to use the store version and task scheduler does not work unless 'only when user is logged on' option is checked, but the downside of this workaround is its popping up annoying shell window anytime it runs a script.

aki-k commented 1 year ago

but the downside of this workaround is its popping up annoying shell window anytime it runs a script

Maybe you could try running it as another user than the one you login to Windows with?

bavtan commented 1 year ago

but the downside of this workaround is its popping up annoying shell window anytime it runs a script

Maybe you could try running it as another user than the one you login to Windows with?

but i need to run it regardless of who logged in, as like it was used to work before but store version broke everything,

DesktopECHO commented 1 year ago

See also this insideous bug affecting my WSL projects. Applies to Windows 10 and Windows 11 22H2:

Windows 11 22H2 upgrade breaks "Run whether user is logged on or not" scheduled tasks

Windows Version:

21H2 -> Scheduled Task OK! 22H2 -> Clean OS install -> Scheduled Task OK! 22H2 -> Upgrade from 21H2, user profile is present before upgrading to 22H2 -> TASK FAILED 22H2 -> Upgrade from 21H2, new user profile created after upgrade and new task created -> Scheduled Task OK!

It appears that something in the 21H2 -> 22H2 upgrade process causes existing profiles to have this trouble.
Creating a NEW user profile and Scheduled Task to "run whether the user is logged on or not" works reliably! This is not a fix for what looks like a bug in the Windows upgrade process, but it does help narrow down the issue.

aGrimRepoMan commented 1 year ago

Just an added data point: Believe issue is not restricted to WSL2 nor tied to powershell scripts. I see same issue with WSL1 on Windows 10 when running Windows Task Scheduler task with program set to "C:\WINDOWS\System32\wsl.exe" and arguments set to "-d Debian-BackupPC -u root service ssh start", i.e. without invoking intermediate powershell or batch command file. Windows Task Scheduler previously returned success code 0, but for several months now is returning 2147942401.

As others have noted, I started seeing this only after upgrading to 2022H2 and being prompted to install WSL from Microsoft store. Non-ideal workaround is to reconfigure task to" run only when user is logged in" and add a user login trigger.

Installation Details:

  Edition   Windows 10 Home
  Version   22H2
  Installed on  ‎2020-‎06-‎17
  OS build  19045.2728
  Experience    Windows Feature Experience Pack 120.2212.4190.0
DesktopECHO commented 1 year ago

Windows Task Scheduler previously returned success code 0, but for several months now is returning 2147942401.

I don’t think it’s related to the version of WSL at all. If you create a new user, does the task also fail for that user? I’ve observed this issue doesn’t appear when a user is created after the 22H2 upgrade.

aki-k commented 1 year ago

@aGrimRepoMan

I see same issue with WSL1 on Windows 10 when running Windows Task Scheduler task with program set to "C:\WINDOWS\System32\wsl.exe" and arguments set to "-d Debian-BackupPC -u root service ssh start", i.e. without invoking intermediate powershell or batch command file. Windows Task Scheduler previously returned success code 0, but for several months now is returning 2147942401.

Try if these steps help:

1) remove admin rights from the user running that scheduled task

2) define the scheduled task program as:

C:\Windows\System32\cmd.exe /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

Edit: You might have to add "Log on as a batch job" permissions for the user running the task in:

secpol.msc: Security Settings/Local Policies/User Rights Assignment/Log on as a batch job

Edit 2: Log on as a batch job

When you use the Add Scheduled Task Wizard to schedule a task to run under a particular user name and password, that user is automatically assigned the Log on as a batch job user right.

cheng-chi commented 1 year ago

See also this insideous bug affecting my WSL projects. Applies to Windows 10 and Windows 11 22H2:

Windows 11 22H2 upgrade breaks "Run whether user is logged on or not" scheduled tasks

Windows Version:

21H2 -> Scheduled Task OK! 22H2 -> Clean OS install -> Scheduled Task OK! 22H2 -> Upgrade from 21H2, user profile is present before upgrading to 22H2 -> TASK FAILED 22H2 -> Upgrade from 21H2, new user profile created after upgrade and new task created -> Scheduled Task OK! It appears that something in the 21H2 -> 22H2 upgrade process causes existing profiles to have this trouble. Creating a NEW user profile and Scheduled Task to "run whether the user is logged on or not" works reliably! This is not a fix for what looks like a bug in the Windows upgrade process, but it does help narrow down the issue.

I encountered the same issue. It was resolved by

  1. Go to your task in Task Scheduler -> Properties -> General Change User or Group
  2. Enter "Administrators" in "Enter the object name to select" box
  3. Click "Check Names"
  4. Click Ok
  5. Click Ok (for properties)
AdamDanischewski commented 1 year ago

Same as cheng-chi, had something similar but fixed it eventually by modifying the user - also be careful about run only when user is logged in. If you choose administrator, make sure that isn't checked off. Also I didn't have much luck running wsl.exe directly from Task Scheduler - instead create a ps1 powershell wrapper script to call. Put the full path to Powershell (PS> gcm powershell), then add options -executionpolicy bypass -F "c:\path\to\your\wsl_run_script.ps1".

eur2fe commented 1 year ago

also be careful about run only when user is logged in

The whole point of this ticket is to be able to run WSL2 in session 0, i.e. like a service without a console or GUI. This implies that the task scheduler option Run whether user is logged in or not is checked, as stated in the issue.

As a minimal repo, run the following commands in PowerShell:

$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\wsl.exe" -Argument "-- touch ~/i-exist-so-i-ran"
Register-ScheduledTask -TaskName "Test WSL session 0" -User "NT AUTHORITY\SYSTEM" -Action $action
Start-ScheduledTask -TaskName "Test WSL session 0"

When you then look at the task status, it will indicate failure (error code 1):

PS C:\Windows\system32> Get-ScheduledTaskInfo -TaskName "Test WSL session 0"

LastTaskResult     : 1

Just confirmed that using the current WSL-Version: 1.2.0.0

aki-k commented 1 year ago

@eur2fe

Try defining the program to start as:

C:\Windows\System32\cmd.exe /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

I was able to start it automatically as a Windows service (https://github.com/microsoft/WSL/issues/8835#issuecomment-1446474057)

eur2fe commented 1 year ago

@aki-k Thank you for your suggestion, but it does not work.

Using cmd /k leaves a dangling cmd.exe in session 0 behind, which may have tricked you into reasoning that wsl.exe is running (which it is not).

BTW: /dupe https://github.com/microsoft/WSL/issues/9231

aki-k commented 1 year ago

reasoning that wsl.exe is running

Yes it's running automatically after boot, when started through a Windows service.

eur2fe commented 1 year ago

Yes it's running automatically after boot, when started through a Windows service

I think you are using an old version of WSL. Can you post your wsl --version details? The current version is 1.2.0.0.

aki-k commented 1 year ago

@eur2fe I'm using that v1.2.4 that was just released a few days ago.

I seem to have skipped one important step in the setup process. You have to install the WSL2 Linux kernel update package for x64 machines from https://aka.ms/wsl2kernel

I did the install of wsl_update_x64.msi as the non-admin Windows user that is running the startwsl Windows service. Because I've removed local admin rights from the user running the service, the msi installer asks for the Administrator password.

There's still an issue with this kind of setup. If you login to Windows with that non-admin user account, its Ubuntu-20.04 WSL 2 instance will be shut down. You can still use "runas /profile /env /user:accountname cmd.exe" from another account to access it.

Now both sshd and tailscaled start automatically on boot in the WSL 2 Ubuntu VM and I can access the VM remotely.

Irupt commented 1 year ago

Hello, any news on this important bug?

I tried all the suggested solutions, none worked.

This is a core feature, keep us posted

luffjr commented 1 year ago

I also cannot get WSL2 running on system startup, Windows Server 2022 + WSL (1.1.3) + Ubuntu 20.04 LTS

I didn't use the Microsoft Store version, afaik, I just did wsl --install in powershell.

eggachecat commented 1 year ago

+1

ghost commented 1 year ago

/dupe #9231

microsoft-github-policy-service[bot] commented 1 year ago

Hi! We've identified this issue as a duplicate of another one that already exists in this repository. This specific instance is being closed in favor of tracking the concern over on the referenced thread.

Thanks for your report!

astuomi commented 11 months ago

For anyone who ends up finding this as the Google top search hit:

There is a fix in the WSL September 2023 update.

Steps to solve the issue:

  1. Upgrade WSL to the latest (pre-release) version with wsl --update --pre-release
  2. Point the Task Scheduler executable directly at "C:\Program Files\WSL\wsl.exe". IMPORTANT: There are multiple locations for the WSL executable with this update - the one under Program Files is the only one that will work. ¯\_(ツ)_/¯

Confirmed working for me on Win10 and WSL 2.0.1.