Why do weekly tasks created via PowerShell using a different user fail with error 0x41306
Asked Answered
L

7

11

We have some scripts that create scheduled jobs using PowerShell as part of our application. When testing them recently, I noticed that some of them always failed immediately, and no output is ever produced (they don't even appear in the Get-Job list).

After many days of tweaking, we've managed to isolate it to any jobs that are set to run weekly. Below is a script that creates two jobs that do exactly the same thing. When we run this on our domain, and provide credentials of a domain user, then force both jobs to run in the Task Scheduler GUI (right-click -> Run), the daily one runs fine (0x0 result) and the weekly one fails (0x41306).

Note: If I don't provide the -Credential param, both jobs work fine. The jobs only fail if the task is both weekly, and running as this domain user.

I can't find information on why this is happening, nor think of any reason it would behave differently for weekly jobs. The "History£ tab in the Task Scheduler has almost no useful information, just "Task stopping due to user request" and "Task terminated", both of which have no useful info:

Task Scheduler terminated "{eabba479-f8fc-4f0e-bf5e-053dfbfe9f62}" instance of the "\Microsoft\Windows\PowerShell\ScheduledJobs\Test1" task. Task Scheduler stopped instance "{eabba479-f8fc-4f0e-bf5e-053dfbfe9f62}" of task "\Microsoft\Windows\PowerShell\ScheduledJobs\Test1" as request by user "MyDomain\SomeUser" .

What's up with this? Why do weekly tasks run differently, and how can I diganose this issue?

This is PowerShell v3 on Windows Server 2008 R2. I've been unable to reproduce this locally, but I don't have a user set up in the same way as the one in our production domain (I'm working on this, but I wanted to post this ASAP in the hope someone knows what's happening!).

Import-Module PSScheduledJob

$Action =
{
    "Executing job!"
}

$cred = Get-Credential "MyDomain\SomeUser"

# Remove previous versions (to allow re-running this script)
Get-ScheduledJob Test1 | Unregister-ScheduledJob
Get-ScheduledJob Test2 | Unregister-ScheduledJob

# Create two identical jobs, with different triggers
Register-ScheduledJob "Test1" -ScriptBlock $Action -Credential $cred -Trigger (New-JobTrigger -Weekly -At 1:25am -DaysOfWeek Sunday)
Register-ScheduledJob "Test2" -ScriptBlock $Action -Credential $cred -Trigger (New-JobTrigger -Daily -At 1:25am)

Edit: Added to Connect as suggested by snover:

https://connect.microsoft.com/PowerShell/feedback/details/776801/weekly-tasks-created-via-powershell-using-a-different-user-immediately-fail-with-error-0x41306

Edit: Some additional info from Jeff Hicks

I used your code to create the same jobs on my 2008 R2 box running PS v3. Both jobs ran fine from PowerShell using Start-Job. But in the GUI, I got the same error for the weekly job.

I get the same result on Windows 8. Something is telling the task service to abort. I tested some other settings but they had no effect. I looked through all of the logs I could think of and all they show is the job starting, PowerShell loading and then the task scheduler cancelling.

I reset the weekly task to run today a little bit ago and it still failed. I also tested a weekly task doing something other than PowerShell and it ran just fine.

I changed the weekly job to use the same account as the current user and it ran just fine. Changed it back to the other account and it failed again. I have no idea about the correlation between the trigger and account.

Lohner answered 17/1, 2013 at 12:18 Comment(21)
0x41306 means that the task was terminated by user. Ref: msdn.microsoft.com/en-us/library/windows/desktop/… What happens, if you switch the schedules vice versa?Thoughtful
I'd looked up the code, but it makes no sense. It's not termianted by the user at all :( Not sure what you mean by switching the schedule? The test script creates two tasks that are the same; the daily one always works; the weekly one always fails.Lohner
Change Test2 to weekly schedule. Does it fail? What happens after you change its schedule back to daily one?Thoughtful
@Thoughtful Yes, it fails if we change it to weekly (even through the GUI). The schedule is the only difference (besides name, but these don't make any difference), so this is kinda expected :(Lohner
Switch the order of the two last lines in your script. Does the same job still fail, or is it the other one now? If it's the other one, I'd suspect there's some object - probably the credentails - that's only valid for one use or something.Roquelaure
Import the PSScheduledJob module, then find the id of the scheduled job with Get-Job and dump the job's output with Receive-Job -Id <id> - just is case it is something with the script itself.Nahshu
@KeithHill there is no output, it doesn't run. The PS being executed is in my code sample, it's the same in both cases and just a string :(Lohner
@Roquelaure I thought that too, but it doesn't matter. In the real script we create around 10 jobs, and the weekly ones (2nd and 8th) failed :(Lohner
maybe take powershell out of the equation to see if its part of the equation , or the OS. create scheduled tasks manually with the same triggering options. have them do something benign as outputting ipconfig to a file, and then trigger them both manually.Inaccessible
@Inaccessible we've done this (and Jeff Hicks did too). Only happens it's a PS task, and set to Weekly and running as another user. Makes no sense :-(Lohner
Did you ever find a solution to this? I'm having this same problem and ONLY happens whenever you set it to run as another user, can't seem to figure out what is causing it. Get the same error too, "as requested by user ... how is it that a user requests to terminate ... "Fiat
@Myles unfortunately not. I was recently asked for a link by Lee Holmes here twitter.com/Lee_Holmes/status/535870040508096513 but no useful response.Lohner
Ugh, and this is on Server 2012 as well :( Kind of defeats the entire purpose of using different credentials if we can't even set it to another userFiat
OKAY, so I did figured out the problem, and it's 100% with permissions. Regarding the scheduled job, as long as you are running the script as Administrator (or exe if compiled) it should not be removed. I'm using Powershell Studio to compile to exe so I just included a manifest requiring elevated privs to resolve this .... BUT that doesn't resolve the fact that you CANT DISABLE/ENABLE jobs even if you have admin perms ... so again I pass one road block just to hit another ... UGH!Fiat
@myles this wouldn't explain why weekly schedules fail, yet any other schedule works?Lohner
True, and the only thing I can think is maybe somehow the user account is "cached" in some sense and thus the weekly fails. I'm going to test mine and see what happens after a week or two of running and will report back.Fiat
I will say though, I had this exact same error when registering the job with credentials (different domain admin) but NOT running the script/exe as an Administrator, once I ran as Admin it no longer immediately gets removed "as requested by user"Fiat
@myles the issue is totally reproducible for me without any sort of permission changes, changing the schedule reliable causes/fixes the issue. I don't see how it can be permissions related :(Lohner
Hi, guys, I recently have this error as well, on windows server 2008 R2 Standard. And this happens when I change the running time(as client required) of a daily task which takes only 30sec, using administrator. Later I worked around this by separating my cmds. But still get this error after the first cmd(that is why the rest cmds can not execute before). Lucky is that the cmd executes correctly, but dose not stop correctly until hit the setted time limitation and get the 0x41306 error. Any idea for this case?Kandicekandinsky
Looks like your Connect case has been deleted. The link is broken, at least.Pinpoint
@BaconBits Yeah, I noticed that too. I'm not surprised though; it wasn't being used at all! I was told the MVPs had been given it and the PoSh team didn't use it directly... seems something broke down somewhere :/Lohner
T
1

I had a similar problem when creating scheduled task but I don't remember if it was based on the day schedule. I found changing over to gMSA account to run our scheduled task? Which allowed us to set the task to run whether the user was logged on or not. Otherwise you must provide username and password and cannot have the option of user logged on or not.

Terryn answered 28/5, 2016 at 20:27 Comment(0)
T
1

i finally found the solution to this behaviour. I scheduled a task to be executed every sunday to run a powershell script. The script on its own ran fine. Then I tried to start it manually in task scheduler. This ended in error 41306. After reading your comments here I changed the schedule not to first run the next sunday but to start on the last sunday (so the start date is in the past). After that I could immediately start it without any problem.

Theophilus answered 20/10, 2016 at 13:40 Comment(1)
How did you "change the schedule"? The problem is with tasks created via PoSh, so if you change it in Task Scheduler that's not really a solution. If you're able to change this in the PoSh script, can you explain how?Lohner
M
0

The default job options might provide a clue. There are many default values that can prevent a job from running. Some of these might be specific to your environment. More info here: http://technet.microsoft.com/en-us/library/hh849674.aspx

If this isn't it, please let me know. I'd like to follow this topic and get this scenario into that troubleshooting guide.

Thanks, June Blender (juneb) Senior Programming Writer, Microsoft

Millwater answered 17/1, 2013 at 18:52 Comment(2)
Over a year on and no response on Connect (no real surprise; same with other PoSh bugs). This is 100% reliably reproducible and CRASHING. Any idea why it's being ignored?Lohner
Two years; and still no response. Only happens for jobs that are both Weekly and another user; changing either of those, the error vanishes. Does MS not support PoSh?Lohner
U
0

In my case, when I looked at the history of the task, I found that when the task was being created, it was using notepad.exe to attempt the execution (because notepad.exe was set as the default for opening .ps1 files; because it was a fast way to edit the scripts). This was obviously causing a problem though.

To fix it, I right-clicked one of my PS1 scripts and choose open with, and choose the default of %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe (path may vary for each person reading this, so I'd recommend just pulling up the properties of the PowerShell shortcut to get your specific path).

I then tried running the task again - Success!

Unriddle answered 6/2, 2017 at 18:6 Comment(2)
This doesn't sound like the same issue; since that would've failed regardless of the schedule.Lohner
This was the answer to my own 0x41306 issue, thanks!Mansard
S
0

I think the solution though is open the task, go to settings, untick "stop the task if it runs longer than: x". I think it just timed out so it was closed.

Shaynashayne answered 7/1 at 4:5 Comment(1)
This is not the case, the task never started. There were instructions to repro the issue in the question, although it's been over 10 years since I posted this and I don't know if it's still an issue. I haven't used PowerShell tasks since this because we failed to get any support for issues like this 😕Lohner
S
0

Coming to this ancient question with a possible solution that worked for me. I still have a customer with a Server 2012 and I've just hit this issue (or a very similar one?).

In the logs I did have something before the "Task stopping due to user request" log entry in the History tab, as shown below:

sequence of events logged in the history tab

Notice I have Task triggered by user cause I could also reproduce the issue if I manually triggered the task. At the time of the screenshot above, the task was set for 4 hours in the specific (and only) trigger settings. Before that, I had it set for 8 hours and it was being consistently stopped after 15min. So wonder how fast the trigger will engage if you had it set for, say, 1 hour?

If you didn't have any of the previous steps in the flow, it's possible something else was erasing the history log. Even if it was an immediate stop, the Action started should have been logged at some point.

So, for the scenario described above at least, you should disable the time limit in the task trigger completely (not in the general task settings. Then the task is not killed early.

uncheck the "stop task if it runs longer than:


It looks like the timeout interval in the individual task triggers are incorrectly labeled. In my tests, setting to 8 hour, the task was being killed consistently in 15 minutes, setting down to 4 hour, 10 minutes.

Some points that might isolate the scenario:

  • Seems like weekly tasks only are affected (at least the monthly ones aren't
  • Doesn't matter what's triggered or what created the task (running cygwin task set up manually here)
  • Can be reproduced by manually triggering the task (run)
  • In my case the task was set to use Administrator credentials

Don't mistake the checkboxes. The general settings are not affected by this issue so it's okay to leave it checked for the desired time, and the task shall be terminated in the expected time:

it's okay to keep the task time limit in general task settings

To address the issue:

  1. open the task's Properties,
  2. switch to the Triggers tab
  3. Edit the trigger (or triggers if more than one, esp. weekly ones)
  4. uncheck the Stop task if it runs longer than: option (screenshot above).

It may be possible to choose the longest time limits in the dropdown next the option to give more run time while still limiting the specific trigger, but from my tests they'd last much much less than what they report.

The positive side is that even though the specific trigger won't terminate a long/stuck running task, the general settings' limit will, so it's not necessary to lose much of the task reliability in order to keep the task weekly, fortunately!

Skittle answered 23/8 at 18:52 Comment(3)
Notice: your tasks never started possibly due to the default time selected in that trigger's dropdownSkittle
In my case, the task wasn't being terminated early, it just never started. It immediately failed with the error quoted, but the actual task was never invoked.Lohner
yes, I've just added that first comment up front cause I knew your case. too bad I doubt you can ever reproduce this anymore, unless you still have some old windows servers sitting around :) By your report you have ["Task stopping due to user request" and "Task terminated"] if you don't have corresponding ["Task Started" "Created Task Process" and "Action Started"] then you had another underlying problem wiping the log entries. I'll add this flow to the answer to clarify where my answer appliesSkittle
I
-1

So scheduled jobs run in the task scheduler, but there isn't a really tight integration. when you register a scheduled job, a scheduled job definition is created, and hopefully a windows scheduled task options. there is NO scheduled job instance job created until windows scheduled task has 1) successfully triggered that scheduled job, and 2 its run far enough successfully, that its created the instance.

I would have preferred that if in a case the scheduled job failed, PowerShell would at least query the scheduled task engine and find out that an instance started, and failed, and gets the error, or whatnot.

So basically when you registered it you register it with a trigger, which may or may not happen, and various things can occur where it fails, before PS even gets run..

For instance lets say you specific it to run under certian creds and there is something wrong with the credentials, or maybe the permissions change AFTER you have registered it.. When the trigger happens, windows won't be able to start the scheduled task, and therefore the scheduled job code won't tell PS anything about it.

One interesting case happened to me when i was doing some demos. In testing , on my laptop it would register it, and trigger 4 seconds later, then i could see the job instance, then it would finish and i could get the results.

however it would ALWAYS fail, when i'd demo it. And it was because by default options scheduled tasks won't run when running on battery, instead of being plugged in, and when doing my demos i'd grab my laptop and go show people, and i wasn't plugged in.

its sad because from the PS side , it looks like nothing happened, when as far as the scheduled task engine is concerned, there is a history that it tried to run and failed because of specific error codes and messages.

if you want to be able to see a job with failed status and reason in the next version , vote up my bug on connect

https://connect.microsoft.com/PowerShell/feedback/details/737587/psv3-scheduledjobs-if-a-trigger-fails-there-is-no-failed-instance-example-uses-multiple-triggers-to-do-this

Inaccessible answered 17/1, 2013 at 19:9 Comment(3)
I don't think our problem is anything like this, as one works and the only difference is the schedule. However, your suggestion is good, I'll up vote that when back at a PC!Lohner
have you looked at the scheduled task entry (in windows scheduled task UI) itself and seen what its history looks like?Inaccessible
Yep, it reports that the task was cancelled by the user! See the quotes from Jeff Hicks at the bottom of my question, taken from here plus.google.com/113181962167438638669/posts/HLHwcZMCB95Lohner

© 2022 - 2024 — McMap. All rights reserved.