A workaround for the fact that a scheduled task in Windows requires a user to be logged in

AlexC picture AlexC · Aug 4, 2011 · Viewed 45.6k times · Source

I am running a small executable created by a third party that needs to run at regular intervals on a Windows 2008 server. This executable effectively ETLs information from one system to another and needs to run every hour or so around the clock. As part of its processing the executable launches a small Windows Forms type UI.

I have set up a scheduled task to call the file and this works ONLY if the user under which the task is configured to run is logged onto the machine (either locally or via Remote Desktop). If I set the task to run as another user, or set the task to run when the user is not logged, on the scheduled task executes and errors. I have tried running as different users including Administrator user and System user. Is there any possible workarounds (without changing the third party code which I have no access to) which would allow this code to be run without a specific user logged in.

Answer

Breeze picture Breeze · May 13, 2015

This article shows how to create a task that does not require any login: https://www.scriptjunkie.us/2013/01/running-code-from-a-non-elevated-account-at-any-time/

The described procedure is as follows:

First, create a scheduled task to run your command with default options as the current user (this will by default create a scheduled task that only runs when you are logged in):

schtasks /create /tn mytask /SC HOURLY /TR "calc"

Then export the task as XML:

schtasks /query /XML /tn mytask > temp.xml

and delete the task:

schtasks /delete /tn mytask /f

Then open the xml file, and replace the line <LogonType>InteractiveToken</LogonType> with <LogonType>S4U</LogonType>

This can be done with the following commands assuming powershell is on the system: powershell -Command "Get-Content '.\temp.xml' | foreach {$_ -replace 'InteractiveToken', 'S4U' }" > new.xml move /y new.xml temp.xml

Now recreate the task from the modified XML file:

schtasks /create /xml temp.xml /tn mytasks

and remove your temp file:

del /f /q temp.xml