问题
I have a batch file which is set to run as a Scheduled Task on Windows Server 2012.
When I run the batch file by hand from the command line, it works. When I right-click on my task in Task Scheduler and manually run it, it still works fine.
But, if I let the task run according to the schedule set for it... then it seems to work sometimes, but not others.
I have already set the task to run as a given user; I have set its 'Start in' directory correctly; I have tried giving it highest privileges. None of that helps.
回答1:
The basic answer is that the batch file for the task is running, and that the last step of the task is returning 0x0
. If the task is apparently 'not doing anything', it is because some earlier step of the task is failing silently
Why? In my case, and I think this could easily effect other people, the answer is that the batch file for a scheduled task sees different environment variables depending on whether the user it runs as is currently logged in or not.
More Detail:
In particular, if the task is set to run as Administrator, then while Administrator is logged in the task sees one set of variables (whether it is run manually or on the schedule), but when Administrator is not logged in, it sees a different set of variables.
This can be very hard to debug - basically, you need to put in a lot of logging!
When you are running a batch file as a Scheduled Task on Windows Server 2012, it only sees shared environment variables. It does not see the user specific environment variables for the user you have set it to run as, unless the user in question is currently logged in.
You can see the problem in action by putting SET > test.txt
into a batch file on its own, and running it as a task in different circumstances (manually; on a schedule when logged in; on a schedule when not logged in).
UPDATE:
From more detailed testing, it seems that when the user which the task is set to run as is not logged in, the variables USERDNSDOMAIN,
USERDOMAIN
and USERNAME
do get set correctly for that user anyway. The variable USERPROFILE
gets set incorrectly to the value for the Windows default user (i.e. C:\Users\Default
). Everything else gets set incorrectly to the set of shared environment variables only (note that this is obviously not the correct set for the specified user, and is also not even the correct set for the Windows default user, which should get its user specific environment variables from HKEY_USERS\.Default\Environment
).
Note:
This is not the same issue as windows 7 task scheduler doesn't use updated path , and in fact changes to any shared environment variables, including PATH
, do get seen straight away (on the tests I did, on Windows 2012 R2), with no restart of any process.
来源:https://stackoverflow.com/questions/32589381/why-is-my-scheduled-task-updating-its-last-run-time-correctly-and-giving-a-l