dahall / taskscheduler Goto Github PK
View Code? Open in Web Editor NEWProvides a .NET wrapper for the Windows Task Scheduler. It aggregates the multiple versions, provides an editor and allows for localization.
License: MIT License
Provides a .NET wrapper for the Windows Task Scheduler. It aggregates the multiple versions, provides an editor and allows for localization.
License: MIT License
Hi,
I tried to merge TaskScheduler together with german localized resources, like here: https://taskscheduler.codeplex.com/discussions/351311
Added these 3:
de\Microsoft.Win32.TaskScheduler.resources.dll
de\Microsoft.Win32.TaskSchedulerEditor.resources.dll
de\TimeSpan2.resources.dll
ILSpy shows .de. resources are there in merged library:
But dialog is not localized. Perhaps i missed something?
I start my project with
Dim ci As CultureInfo = New CultureInfo("de-DE")
Thread.CurrentThread.CurrentCulture = ci
Thread.CurrentThread.CurrentUICulture = ci
if I reference original libraries - localization is ok
Thanks
Hello!
First of all let me thank you for such an amazing piece of work.
And I'm sorry for opening a new issue due to my only personal small need.
So would you mind helping me with localization to Russian language?
What exactly I need to be localized is TaskEditDialog and all information related to trigger descriptions.
BUT! There is one more problem. I am not able to build this project on my own because of lower VS version than required.
Is there any chance of you providing me with rebuilt dll after I prepare aforementioned translations?
I am trying to create a task that runs under the "SYSTEM" user account, and I am able to do so using the RegisterTaskDefinition as such: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount). If I manually open up Windows Task Manager, I can see that it is still set to run as "SYSTEM."
However, if I create a TaskEditDialog and call ShowDialog for that task, the user property resets to the logged on user, rather than "SYSTEM." I can see my user name in the "When running the task, use the following user account" field, and when I click OK, it updates the Task to use my user name. However, if I click "Cancel," the Task (as visible in Windows Task Scheduler) still reflects the original user of "SYSTEM."
It seems as though the TaskEditDialog is intentionally resetting the user property on the Task to the currently-logged in user, disregarding the user that may have been purposefully set prior to the ShowDialog call.
How can we set the Priority property to a precise level (for example, 4).
Assigning 'Normal' to the Settings.Priority property is using '5' as the level. But what if we need to set it to 4?
Trying to change td.XmlText doesn't produce any effect.
td.Settings.XmlText comes back as unimplemented property.
This isn't strictly related to your library, but perhaps you or other users of this library have run into and know of a solution. It seems under Windows 10, it's no longer possible for an ordinary user to view tasks created by other users or administrators. Under previous versions of Windows, it was possible to modify the ACL's on C:\Windows\System32\Tasks to allow lower privileged users to read and/or modify tasks that they wouldn't otherwise be able to access.
Does anyone know a way around this Windows 10 limitation?
If OSVersionInfo.Name.Equals("Windows Server 2003") Or OSVersionInfo.Name.Equals("Windows XP") Then 'V1: Win XP, Win 2003 Server
Using ts As New TaskService()
' Create a new task definition and assign properties
Dim td As TaskDefinition = ts.NewTask
td.RegistrationInfo.Description = "Something"
td.RegistrationInfo.Author = "Someone"
td.Settings.RunOnlyIfIdle = False
td.Settings.DisallowStartIfOnBatteries = False
td.Settings.StopIfGoingOnBatteries = False
td.Settings.WakeToRun = True
td.Settings.RunOnlyIfNetworkAvailable = True
td.Settings.RunOnlyIfLoggedOn = False
Dim wt As New WeeklyTrigger()
wt.StartBoundary = Date.Today.AddDays(-1) + TimeSpan.FromHours(horario.hora) + TimeSpan.FromMinutes(horario.minuto) 'Inicia hoy a la hora programada
Dim diasArray() As String = dias.Split(",")
wt.DaysOfWeek = ConvertArrayToDayOfWeek(diasArray)
wt.WeeksInterval = 1
td.Triggers.Add(wt)
td.Actions.Add(New ExecAction(ruta, argumento))
ts.RootFolder.RegisterTaskDefinition("Some_Task",
td)
End Using
End If
Please add an example for TaskEditDialog Class.
TODO (optional): Describe a specific scenario you would like to see addressed.
Help Topic: https://dahall.github.io/TaskScheduler/html/T_Microsoft_Win32_TaskScheduler_TaskEditDialog.htm
There are many tasks created on a Server machine using this library. Now the Server has been upgraded from Windows Server 2012 R2 to Windows Server 2016. All the tasks in the old server was exported and now imported in the new Server.
All the tasks are running correctly. But somehow when my application tries to find the tasks via FindTask(), it returns null. Below is the code I am using to find the task.
TaskService st = new TaskService();
Task oTask = st.FindTask("{A689610E-EC51-4288-A8EB-3847B4AB152D}");
Below is the snap of the Task scheduler with the same task working normal.
Steps to reproduce the issue:-
st.FindTask("T1");
it returns null.I am facing this issue on the Server and not able to read the tasks at all since I can't find them.
Please suggest a way to read all these tasks.
Thanks,
Jeet Doshi
I have an issue where it only occurred on One Time trigger with repetitive configured. It doesn't run on the last/final "Next Run Time" and it only happens when the task is created from code.
For example:
When i set it to start the schedule on 10:00:00 AM and to repeat the task every 1 minute for a duration of 2 minutes. The task executed at 10:00:00 AM & 10:01:00 AM, but at 10:02:00 AM did not get executed even though the "Next Run Time" did specify to run at 10:02:00 AM in task scheduler window.
Did not find anything on history tab and the event log. There is no error and it did not stamp any information for 10:02:00 AM.
I have tried to manually create the task through the task scheduler window and it doesn't have this problem.
Version tried on "2.5.21" & "2.6.3".
Tested on Windows Server 2016 & Windows Server 2012 R2.
`using (var taskService = new TaskService())
{
var taskSchedulerFolder = @"Tasks Folder\CustomSchedulerProcessor";
var taskDefinition = taskService.NewTask();
var registrationInfo = taskDefinition.RegistrationInfo;
registrationInfo.Date = DateTime.Now;
var settings = taskDefinition.Settings;
settings.StartWhenAvailable = true;
settings.AllowDemandStart = false;
settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
settings.DisallowStartIfOnBatteries = false;
settings.StopIfGoingOnBatteries = false;
var trigger = new TimeTrigger();
trigger.StartBoundary = DateTime.Now.AddSeconds(5);
trigger.Repetition.Interval = new TimeSpan(0, 1, 0);
trigger.Repetition.Duration = new TimeSpan(0, 2, 0);
trigger.Repetition.StopAtDurationEnd = false;
using (trigger)
{
taskDefinition.Triggers.Add(trigger);
using (var execAction = new ExecAction(@"E:\OneTimeConsole.exe"))
{
taskDefinition.Actions.Add(execAction);
var logonUser = string.Empty;
using (var currentWindowsIdentity = WindowsIdentity.GetCurrent())
{
logonUser = (new WindowsPrincipal(currentWindowsIdentity)).Identity.Name;
}
taskDefinition.RegistrationInfo.Author = logonUser;
taskService.GetFolder(taskSchedulerFolder).RegisterTaskDefinition(Guid.NewGuid().ToString().Replace("-", string.Empty), taskDefinition, TaskCreation.Create, logonUser, logonType: TaskLogonType.InteractiveToken);
}
}
}`
On windows 8 and below (including the server 2012 counterpart) tasks fail indefinitely (remain running till the machine is rebooted, but never actually execute) when the argument passed to them is longer than 260 characters with errorcode 2147942487.
Windows 10 doesn't seem to suffer from this problem (thankfully), could we add a filter/exception for this so other people don't bump their toes on this problem?
When getting the definitions of certain tasks on mostly Windows 2012 servers, I get the following error:
The current version of the native library (1.3) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.4/1.4)
I am running this code on a Windows 7 machine. (Perhaps it needs to be run on a machine with the native library v 1.4 - i.e. a recent server edition of Windows
Any ideas?
Thanks
I am trying to create a task that runs a cmd and after it's done (+ 5 minutes) it deletes itself. If I set up the task without td.Settings.DeleteExpiredTaskAfter and wihtout tt.EndBoundary. It works just fine. Do you have any ideas what I did wrong or what am I missing?
The error I'm getting is "(35,4):EndBoundary:".
Here is my function
private void createTask(DateTime dateAndTime, string username, string groupName, string computer_name)
{
using (TaskService ts = new TaskService(computer_name))
{
TaskDefinition td = ts.NewTask();
TimeTrigger tt = new TimeTrigger();
tt.StartBoundary = dateAndTime;
tt.EndBoundary = dateAndTime + TimeSpan.FromMinutes(5);
td.Settings.StartWhenAvailable = true;
td.Settings.Hidden = true;
td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(10);
td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
td.Settings.DisallowStartIfOnBatteries = false;
string parametr = "/c net localgroup " + groupName + " /delete " + username;
td.Actions.Add(new ExecAction("cmd.exe",parametr, null));
ts.RootFolder.RegisterTaskDefinition(@"Automatic Membership Validation", td,
TaskCreation.CreateOrUpdate,"SYSTEM",null,TaskLogonType.ServiceAccount);
}
}
This is how I call the function
createTask(dateTimePicker1.Value, "testuser", "Administrators", "testcomputer");
In all cases dateTimePicker is set-up like this:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd'.'MM.yyyy - HH':'mm";
Hello all,
I can add the task when testing on system using a local login and the TaskLogonType.InteractiveToken option but not for a domain account (Active Directory) account that is currently logged into.
Please advise when you get a chance.
Thanks for your help,
Bob
The latest version of the NuGet package has a dependency on JetBrains.Annotations (>= 11.0.0)
Can this be removed, it seems unnecessary.
TaskScheduler 2.6.3
Hello, I setup a scheduled task to be run by a user in Windows 2016, when I look at that task via the TaskScheduler library, the TaskDefinition.Principal.UserId for this task is an empty string. If I look at the raw XML for the task:
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-#########-##########-##########-####</UserId>
<LogonType>Password</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
I can see the SID instead of the user id which is defined as a possibility (https://msdn.microsoft.com/en-us/library/cc248346.aspx). However, I don't see that SID in any of the fields exposed in the TaskPrincipal object (or anywhere else in the Task object).
Should I expect it to be, or am I possibly doing something wrong? I mentioned Windows 2016, but I don't know if this is really specific to Windows 2016, it just is the only OS I've run into this on. Thanks!
Hi!
I wrote a small class to try to schedule a task using TaskScheduler, but every username I try I get an "Access Denied" error.
I'm logged on a domain account which is administrator of this computer, and the provided XML was exported from a task I scheduled manually directly on Windows with the very same account, but I still get this:
System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
(I tried with simple examples like this one but got the same error)
Example:
using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "My first task scheduler";
// Run Task whether user logged on or not
td.Principal.LogonType = TaskLogonType.S4U;
TimeTrigger trigger = new TimeTrigger();
trigger.StartBoundary = DateTime.Now;
trigger.Repetition.Interval = TimeSpan.FromMinutes(180);
td.Triggers.Add(trigger);
td.Actions.Add(new ExecAction(@"C:\simple.exe", null, null));
ts.RootFolder.RegisterTaskDefinition("TaskName", td);
}
My JobScheduler Class:
public class JobScheduler
{
public String Username { get { return Environment.UserDomainName + "\\" + Environment.UserName; } }
public String Datetime { get { return DateTime.Now.ToString("yyyy-MM-dd") + "T" + DateTime.Now.ToString("hh:mm:ss.FFFFFFF"); } }
public String DateJob { get { return DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "T" + "15:00:00"; } }
public String AppPath { get { return Application.ExecutablePath; } }
public String UserId { get { return WindowsIdentity.GetCurrent().User.ToString(); } }
public JobScheduler()
{
}
public void Schedule()
{
TaskService ts = new TaskService();
Boolean achou = false;
foreach (Task t in ts.RootFolder.Tasks)
{
if (t.Name == Properties.Resources.JOBNAME)
{
achou = true;
}
}
if (!achou)
{
String job = Properties.Resources.Job.ToString();
job = job.Replace("$USERNAME", Username);
job = job.Replace("$DATETIME", Datetime);
job = job.Replace("$DATEJOB", DateJob);
job = job.Replace("$USERID", UserId);
//job = job.Replace("$USERID", "S-1-5-18");
job = job.Replace("$APPPATH", AppPath);
TaskDefinition td = ts.NewTask();
td.XmlText = job;
//ts.RootFolder.RegisterTaskDefinition(Properties.Resources.JOBNAME, td, TaskCreation.CreateOrUpdate, Environment.UserName, null, TaskLogonType.InteractiveToken, null);
ts.RootFolder.RegisterTaskDefinition(Properties.Resources.JOBNAME, td);
}
}
}
My Base XML:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2018-01-10T17:25:54.5633849</Date>
<Author>FABER-CASTELL\CEVINICIUSZH</Author>
<URI>\Horario</URI>
</RegistrationInfo>
<Triggers>
<BootTrigger>
<Enabled>true</Enabled>
</BootTrigger>
<LogonTrigger>
<Enabled>true</Enabled>
</LogonTrigger>
<SessionStateChangeTrigger>
<Enabled>true</Enabled>
<StateChange>SessionUnlock</StateChange>
</SessionStateChangeTrigger>
<SessionStateChangeTrigger>
<Enabled>true</Enabled>
<StateChange>RemoteConnect</StateChange>
</SessionStateChangeTrigger>
<CalendarTrigger>
<StartBoundary>2018-01-10T15:00:00</StartBoundary>
<Enabled>true</Enabled>
<ScheduleByDay>.
<DaysInterval>1</DaysInterval>
</ScheduleByDay>
</CalendarTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>S-1-5-21-1365381750-711603728-1050887974-14290</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT12H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>C:\Users\ceviniciuszh\AppData\Local\Apps\2.0\ZPWZ329E.WY5\JA5NP4R5.YHB\hora..tion_0000000000000000_0003.0000_b91bcafc9e60eb9a\Horario.exe</Command>
</Exec>
</Actions>
</Task>
In Visual Studio 2017 running under .NET 4.5, trying to move from TaskScheduler 2.5.20 to the latest or even the next build up throws the following error on build attempt:
CS0433 C# The type exists in both and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
The class it's referring to is IReadOnlyCollection. Looking at your source code, I see conditional statements; however, it looks like those are not functional.
I have had a few users get the following error but I have no idea what is causing it. Seems like it might be a user logon issue but I'm told they were using the correct Windows logon details. Does anyone know what the error means?
Exception: (23,8):UserId:
at
Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(S
tring Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String
path, TaskDefinition definition, TaskCreation createType, String userId, String password, TaskLogonType logonType, String sddl)
at Microsoft.Win32.TaskScheduler.TaskEditDialog.okBtn_Click(Object
sender, EventArgs e)
Hi,
can you make TaskSchedulerEditor.dll COM-Visible? I am trying to use it from VBA, Microsoft.Win32.TaskScheduler.dll works fine, but not Microsoft.Win32.TaskSchedulerEditor.dll.
Thanks
Alex
How do I code this?
Hi,
what is the right way to add new task to specific folder using dialog? I use such code to add to root folder, tried to specify editorForm.TaskFolder, but task still created in RootFolder.
Using ts As New TaskService()
Dim td As TaskDefinition = ts.NewTask()
Dim f As TaskFolder = ts.GetFolder(strFolder)
td.Actions.Add(strExeFilename)
Dim editorForm As New TaskEditDialog(ts, td, True, True)
editorForm.ShowDialog()
Or, perhaps it is possible to move task to other folder?
Alex
Hi,
First of all, thanks for this project.
The RunEx method takes a "parameters" parameter string[], but crashes if it's null. If you've read the documentation for RegisteredTask.RunEx this is very confusing, as null is a valid value (meaning "no parameters).
Here's the first line that uses the parameter without checking it for null:
TaskScheduler/TaskService/Task.cs
Line 1292 in 2b2e8eb
Thanks again!
Hello, I installed just the Main Library through NuGet.
Since this is not a UI one, I just want english resources. Is that possible?
In Windows any unprivileged user can create a task for yourself in Interactive Token mode ("run only when user is logged on").
Looks like I can't do that via TaskService. I've tried 2 ways:
TaskService.Instance.AddTask("app_"+sid, QuickTriggerType.Logon, path, "-agent");
and
using (var ts = new TaskService())
{
var td = ts.NewTask();
td.Actions.Add(path, "-agent");
var tr = td.Triggers.AddNew(TaskTriggerType.Logon);
td.Principal.LogonType = TaskLogonType.InteractiveToken;
ts.RootFolder.RegisterTaskDefinition("app_" + sid, td);
}
Hi.
I have a simple question but I couldn't find the solution.
What's the code if I want to change the "configure for" settings?
e.g. Windows Vista -> Windows 10
Here is my code:
using (TaskService ts = TaskService.Instance)
{
using (var folder = ts.GetFolder(path))
{
}
}
However, the GetFolder throw an exception sometimes. I checked the the TaskService object when failed and fount it is not connected. Maybe I call the code two freqently?
How could I make sure it will always work?
We use your library, so thank you for making it available and maintaining it. We are looking at moving to .NET Core, and I'm wondering what your plans are for making a .NET Core version available as well.
I've attempted a port of the TaskService
projects, and the only bit I found that wasn't supported is the WindowsImpersonationContext
and the EventLog
stuff.
I'm trying to create a scheduled task to only run on the last day of the month. It doesn't seem like this is possible since the DaysOfMonth variable is required to be between 1 and 31. Is there anyway to have the scheduled task only run on the last day of the month?
I'm sorry if this is obvious to most Windows developers, but I have no idea how to view the help file after running the bat file?
Hello,
im trying to connect to a remote machine to get all task and im using:
using (TaskService ts = new TaskService(computer,user,domain,password)) { EnumFolderTasks(ts.RootFolder); }
but i have this error:
The request is not supported. (Exception from HRESULT: 0x80070032)
or access denied error, but the credentials is right.
Can anyone help me?
Thanks
I'm trying to use the TaskEditor
in one of my UWP projects.
Unfortunately I'm unable to do this, because the library depends on System.Windows.Forms
.
What is the best way to determine the maximum TaskCompatibility supported by the current system?
Please add an example for Task.LastTaskResult Property.
TODO (optional): Describe a specific scenario you would like to see addressed.
Help Topic: https://dahall.github.io/TaskScheduler/html/P_Microsoft_Win32_TaskScheduler_Task_LastTaskResult.htm
How can I use this to make a program run when no input is made for X amount of time?
The selected COM object has its name inserted into the text field, instead of the GUID, this causes a validation error in ComHandlerActionUI.comCLSIDText_Validating
The error is "Invalid GUID for CLSID"
This is the same class I selected in issue #27 .
In a slightly related issue, if you select "Manually Enter CLSID", the OK button is not enabled unless you already tried to select a COM server in the browse list.
I want to restrict trigger type selection in editor (actually I want only calendar triggers and don't want event, logon etc triggers). Is that possible?
Best regards
Kirill
Hi!
How can I end or enable/disable a specific task?
I know the way to remove(ts.RootFolder.DeleteTask("Taskname");) it but I just want to end or disable it.
Hi, I've been looking to contact you since long time.
I tested your product and working perfect but I have a concern.
I'm using VB.Net and want to call a VB method from "Microsoft.Win32.TaskScheduler".
I know that many examples describe about how to open file/application and so on which is external to vb.net ... but I want to call something internal (vb function/method)
How can i do that please? is it possible?
Please see below.
` "td.Actions.Add(New ExecAction("MyMethod()", "c:\test.log"))"
Sub MyMethod()
MsgBox("Working !!!")
End Sub`
After referring to samples "https://github.com/dahall/TaskScheduler/wiki" and the api documentation for RepetitionPattern class "https://dahall.github.io/TaskScheduler/html/T_Microsoft_Win32_TaskScheduler_RepetitionPattern.htm". I'm not able to find how to set the repetitive duration to run "indefinitely". Is it possible to create a task scheduler with the repetition duration is indefinitely?
I have also tried assigning TimeSpan.MaxValue to trigger.Repetition.Duration, but it seems not possible with the application end up throwing exception.
Might be nice to note this in the documentation :=)
System.Runtime.InteropServices.COMException (0x8004130B): There is no running instance of the task. (Exception from HRESULT: 0x8004130B)
at Microsoft.Win32.TaskScheduler.V2Interop.IRunningTask.Refresh()
TaskScheduler/TaskService/Task.cs
Line 891 in 2b2e8eb
Hello,
I am trying to register a task through a web app deployed to an IIS server (Windows Server 2012 R2).
The task is to be run one time only. Action is set to be opening the notepad for testing purpose.
using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Open notepad";
td.Principal.LogonType = TaskLogonType.InteractiveToken;
DateTime time = Convert.ToDateTime(txttime.Text);
DateTime date = Convert.ToDateTime(txtdate.Text);
DateTime send_time = date.Add(time.TimeOfDay);
td.Triggers.Add(new TimeTrigger(send_time));
td.Actions.Add(new ExecAction("notepad.exe", null, null));
//td.Principal.RunLevel = TaskRunLevel.Highest;
TaskFolder tf = ts.GetFolder("\\Microsoft\\Windows\\Notepad");
tf.RegisterTaskDefinition(taskName, td);
}
Use the official one by debugging in localhost is fine but runs into the same error when deployed to server. I have searched over the code and I have no idea what required element or attribute I have missed. Use the wrapper by debugging in localhost also run to an access denied error no matter with or without an admin account.
I am wondering if that is a problem of account permission but adding an account in the Task service config and task registration part only bring more errors like access denied or something like:
Attempted to access an unloaded appdomain. (Exception from HRESULT: 0x80131014)
The tutorial on Task Security provides several approaches but I have tried all possibilities:
I have been struggling in the task registration...
Is it better to get an admin account to get it work ? resulting in a bunch or access error though :(
Thanks in advance for any advice.
Update:
The missing requirement issue was solved by changing the time trigger to
td.Triggers.Add(new TimeTrigger() { StartBoundary = send_time });
locally but the problem is still there to make it work on remote server.
Thanks.
I've created a Console Application which queries 90 remote hosts to list their scheduled tasks. After listing the scheduled tasks of multiple hosts successfully, the wrapper throws the following error on multiple hosts:
The current version of the native library (1.3) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.4/1.4)
Here's the stacktrace:
at Microsoft.Win32.TaskScheduler.Task.GetV2Definition(TaskService svc, IRegisteredTask iTask, Boolean throwError)
at Microsoft.Win32.TaskScheduler.Task.get_Definition()
at ScheduledTasks.ConsoleApp.Program.<>c.g__IsRelevant|2_0(Task x) in C:\path\to\ScheduledTasks.ConsoleApp\Program.cs:line 59
The "line 59" cited interrogates the Definition
property of the Microsoft.Win32.TaskScheduler.Task
object. Trying to access that Definition
property seems to be what's throwing the error? I can provide the full code if that helps. In case it's relevant, the Console Application is running in Windows 7, and all of these queried hosts (those successful and those throwing errors) are running more modern operating systems.
What does this error mean? What can I change to be able to reliably use this Definition
property?
I would like to change the name of a tab (the "triggers" one, to "schedules" because it makes more sense in our project).
Can this be done or do the dialogs use the windows defaults exclusively with no customization possible?
Granted, the comments in the code warn of this, but some basic expressions seem to have incorrect interpretations --
*/15 * * * * should be interpreted as "every 15 minutes" but returns a not-implemented exception.
likewise for alternate expressions with the same meaning: 0-59/15 * * * * and 0,15,30,45 * * * *
Reporting this as a bug as this expression, 0/15 * * * * which should mean every fifteen minutes starting at midnight is instead interpreted as "every hour, at midnight."
Another issue is with commas, i.e. 0 0,12 * * * (midnight & noon daily) which seem to throw the whole interpreter out the window. A job is created with no trigger at all.
If the answer is "not possible" I would completely understand, I'm asking just to be sure.
We have a lot of different end user systems which require regulare updates. Some of those updates require administrative permissions and some of these systems have a password requirement for those permissions.
Creating a task that runs under SYSTEM with the proper access rules added can run these updates.
But some of these updates might hang and require user interaction.
Is there a way to run them as system/administrator/administrators but with the UI part visible for the current user?
Using runas gives some flags that hint that it could, but so far my attempts have been fruitless.
I created a COM server in C#, but when I try to select my COM class as a custom action in the Task editor, I get an exception:
System.ArgumentException occurred
HResult=0x80070057
Message=The object's type must be __ComObject or derived from __ComObject.
Parameter name: o
Source=mscorlib
StackTrace:
at System.Runtime.InteropServices.Marshal.ReleaseComObject(Object o)
at Microsoft.Win32.TaskScheduler.ComObjectSelectionDialog.SupportsInterface(Guid clsid, Guid iGuid)
at Microsoft.Win32.TaskScheduler.ComObjectSelectionDialog.listView1_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e)
at System.Windows.Forms.ListView.OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e)
at System.Windows.Forms.ListView.WmReflectNotify(Message& m)
at System.Windows.Forms.ListView.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Here's the class I created:
using Microsoft.Win32.TaskScheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Scheduler
{
[ComVisible(true)] // This is mandatory.
[Guid("4945B34B-1B63-4a58-B5FE-9627FEFAEA9D")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ITaskRunner
{
}
[Guid("FA40C9BB-410C-46D2-AEC9-8F7D952B3E91")]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[ComVisible(true)]
public class TaskRunner : ITaskHandler
{
public void Start(object pHandlerServices, string data)
{
throw new NotImplementedException();
}
public void Stop(out int pRetCode)
{
throw new NotImplementedException();
}
public void Pause()
{
throw new NotImplementedException();
}
public void Resume()
{
throw new NotImplementedException();
}
}
}
If I remove the Marshal.ReleaseComObject call in SupportsInterface, I can select it fine.
I noticed this with other COM servers on my machine (when randomly selecting), not just mine.
I need to change task security descriptor (add permission for authenticated user), so what I do on Windows 10:
Create a simple task in Scheduled Task Windows snap-in using "Create Basic task" wizard. It's really "simple" - I use word "simple" for all mandatory text fields and don't modify task triggers.
Attached it's xml just for the case simple.xml.txt
Try to change task security descriptor (I inserted this snippet at the end of ShortTest function)
t = ts.GetTask("simple");
var sec = t.GetAccessControl();
var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.AuthenticatedUserSid, null);
var rule = new TaskAccessRule(sid, TaskRights.Read, System.Security.AccessControl.AccessControlType.Allow);
sec.AddAccessRule(rule);
t.SetAccessControl(sec);
sec.AddAccessRule
I get InvalidOperation exception with text "This access control list is not in canonical form and therefore cannot be modified."But, I'm trying to change it same way like I would work with e.g. FileSecurityDescriptor. May be I need to use different approach here?
Best regards
Kirill
Hello,
ich want to connect from a 2016 Server to a win10 Client (remote) and read all Tasks.
I used:
var x = new TaskService($@"\{Host}", _username, _domain, _password);
....
i got the error:
The current version of the native library (1.5) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.6/1.6)
does anyone have a tip for me?
Thanks
A question to the community: I'm considering making a breaking change to the library and introducing nullable TimeSpan and nullable DateTime properties to more accurately reflect how some properties are handled by the native library. For example, the native library would set the EndBoundary value of a trigger to "null" if it was not set. In this library (created before nullable types), that value is artificially recast as DateTime.MaxValue. Please provide your thoughts and votes. It would align this library more to the native library.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.