예제 #1
0
        static void disableRunningZombieTasks()
        {
            using (TaskService ts = new TaskService())
            {
                if (!ts.Connected)
                {
                    RunningTaskCollection runningTasks = ts.GetRunningTasks();
                    TaskFolder KNXFolder = ts.GetFolder("KNX");

                    for (var i = 0; i < runningTasks.Count; i++)
                    {
                        if (runningTasks[i].Folder.Path == "\\KNX")
                        {
                            if (runningTasks[i].NextRunTime < DateTime.Now)
                            {
                                runningTasks[i].Enabled = false;
                                runningTasks[i].Stop();
                            }
                        }
                    }
                }
            }
        }
        internal static void LongTest(TaskService ts, System.IO.TextWriter output, params string[] arg)
        {
            string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            Version ver = ts.HighestSupportedVersion;
            bool isV12 = (ver >= new Version(1, 2));
            bool isV13 = (ver >= new Version(1, 3));
            bool isV14 = (ver >= new Version(1, 4));
            output.WriteLine("Highest version: " + ver);
            output.WriteLine("Server: {0} ({1}); User: {2}\\{3}", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected", ts.UserAccountDomain, ts.UserName);

            output.WriteLine("Running tasks:");
            foreach (RunningTask rt in ts.GetRunningTasks(true))
            {
                if (rt != null)
                {
                    output.WriteLine("+ {0}, {1} ({2})", rt.Name, rt.Path, rt.State);
                    if (ver.Minor > 0)
                        output.WriteLine("  Current Action: " + rt.CurrentAction);
                }
            }

            string filter = arg.Length > 0 ? arg[0] : string.Empty;
            TaskFolder tf = ts.RootFolder;
            TaskCollection tasks = tf.GetTasks(new Wildcard(filter));
            output.WriteLine("\nRoot folder tasks matching \"{1}\" ({0}):", tasks.Count, filter);
            foreach (Task t in tasks)
            {
                try
                {
                    output.WriteLine("+ {0}, {1} ({2}) - {3}", t.Name, t.Definition.RegistrationInfo.Author, t.State, t.Definition.Settings.Compatibility);
                    foreach (Trigger trg in t.Definition.Triggers)
                        output.WriteLine(" + {0}", trg);
                    foreach (var act in t.Definition.Actions)
                        output.WriteLine(" = {0}", act);
                }
                catch { }
            }

            output.WriteLine("\n***Finding defrag task***");
            Task ft = ts.FindTask("*defrag*");
            if (ft != null)
                output.WriteLine("Defrag task found at " + ft.Path);
            else
                output.WriteLine("Defrag task not found.");

            TaskFolderCollection tfs = tf.SubFolders;
            if (tfs.Count > 0)
            {
                output.WriteLine("\nSub folders:");
                try
                {
                    foreach (TaskFolder sf in tfs)
                        output.WriteLine("+ {0}", sf.Path);
                }
                catch (Exception ex)
                {
                    output.WriteLine(ex.ToString());
                }
            }

            if (isV12)
            {
                output.WriteLine("\n***Checking folder retrieval***");
                try
                {
                    const string testFolder = "David's TestFolder";
                    try { tf.CreateFolder(testFolder); }
                    catch (System.Runtime.InteropServices.COMException cex) { if (cex.ErrorCode != -2147024713) throw; }
                    catch { throw; }
                    TaskFolder sub = tf.SubFolders[testFolder];
                    output.WriteLine("\nSubfolder path: " + sub.Path);
                    try
                    {
                        ts.AddTask(testFolder + @"\MyTask", new DailyTrigger(), new ExecAction("notepad"));
                        output.WriteLine(" - Tasks: " + sub.Tasks.Count.ToString());
                        sub.DeleteTask("MyTask");
                    }
                    catch (Exception ex)
                    {
                        output.WriteLine(ex.ToString());
                    }
                    tf.DeleteFolder(testFolder);
                }
                catch (NotSupportedException) { }
                catch (Exception ex)
                {
                    output.WriteLine(ex.ToString());
                }
            }

            output.WriteLine("\n***Checking task creation***");
            try
            {
                TaskDefinition td = ts.NewTask();
                td.Data = "Your data";
                //td.Principal.UserId = "SYSTEM";
                //td.Principal.LogonType = TaskLogonType.ServiceAccount;
                if (isV12)
                    td.Principal.LogonType = TaskLogonType.S4U;
                td.RegistrationInfo.Author = "dahall";
                td.RegistrationInfo.Description = "Does something";
                td.RegistrationInfo.Documentation = "Don't pretend this is real.";
                td.Settings.DisallowStartIfOnBatteries = true;
                td.Settings.Enabled = false;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero; // FromHours(2);
                td.Settings.Hidden = false;
                td.Settings.IdleSettings.IdleDuration = TimeSpan.FromMinutes(20);
                td.Settings.IdleSettings.RestartOnIdle = false;
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.IdleSettings.WaitTimeout = TimeSpan.FromMinutes(10);
                td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
                td.Settings.RunOnlyIfIdle = true;
                td.Settings.RunOnlyIfNetworkAvailable = true;
                td.Settings.StopIfGoingOnBatteries = true;
                if (isV12)
                {
                    td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;
                    td.Principal.Id = "Author";
                    td.RegistrationInfo.SecurityDescriptorSddlForm = "D:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;LS)";
                    td.RegistrationInfo.Source = "Test App";
                    td.RegistrationInfo.URI = "test://app";
                    td.RegistrationInfo.Version = new Version(0, 9);
                    //td.Settings.AllowDemandStart = false;
                    td.Settings.AllowHardTerminate = false;
                    td.Settings.Compatibility = TaskCompatibility.V2;
                    td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
                    td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
                    td.Settings.StartWhenAvailable = true;
                    td.Settings.WakeToRun = true;
                    td.Settings.RestartCount = 5;
                    td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
                    //td.Settings.NetworkSettings.Id = new Guid("{99AF272D-BC5B-4F64-A5B7-8688392C13E6}");
                }
                if (isV13)
                {
                    td.Settings.Compatibility = TaskCompatibility.V2_1;
                    td.Settings.DisallowStartOnRemoteAppSession = true;
                    td.Settings.UseUnifiedSchedulingEngine = false;

                    /*td.Principal.ProcessTokenSidType = TaskProcessTokenSidType.Unrestricted;
                    td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeBackupPrivilege);
                    td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeDebugPrivilege);
                    td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeImpersonatePrivilege);
                    output.Write("Priv: ");
                    //output.Write(td.Principal.RequiredPrivileges[0]);
                    foreach (TaskPrincipalPrivilege item in td.Principal.RequiredPrivileges)
                        output.Write(item.ToString() + ", ");
                    output.WriteLine();*/
                }
                if (isV14)
                {
                    td.Settings.Compatibility = TaskCompatibility.V2_2;
                    td.Settings.Volatile = true;
                    if (td.Principal.LogonType == TaskLogonType.ServiceAccount)
                    {
                        td.Settings.MaintenanceSettings.Exclusive = true;
                        td.Settings.MaintenanceSettings.Period = TimeSpan.FromDays(5);
                        td.Settings.MaintenanceSettings.Deadline = TimeSpan.FromDays(15);
                    }
                }

                // Setup Triggers
                if (isV12)
                {
                    BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger { Enabled = false }); //(BootTrigger)td.Triggers.AddNew(TaskTriggerType.Boot);
                    if (isV12) bTrigger.Delay = TimeSpan.FromMinutes(5);
                }

                DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
                if (isV12) dTrigger.RandomDelay = TimeSpan.FromHours(2);

                if (isV12)
                {
                    EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger());
                    eTrigger.Subscription = "<QueryList><Query Id=\"0\" Path=\"Security\"><Select Path=\"Security\">*[System[Provider[@Name='VSSAudit'] and EventID=25]]</Select></Query></QueryList>";
                    eTrigger.ValueQueries.Add("Name", "Value");

                    td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) });

                    td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleConnect, UserId = user });
                    td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.ConsoleDisconnect });
                    td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteConnect });
                    td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.RemoteDisconnect });
                    td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionLock, UserId = user });
                    td.Triggers.Add(new SessionStateChangeTrigger { StateChange = TaskSessionStateChangeType.SessionUnlock });
                }

                td.Triggers.Add(new IdleTrigger());

                LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
                if (isV12)
                {
                    lTrigger.Delay = TimeSpan.FromMinutes(15);
                    lTrigger.UserId = user;
                    lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000);
                }

                MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger());
                mTrigger.DaysOfMonth = new int[] { 3, 6, 10, 18 };
                mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
                if (isV12) mTrigger.RunOnLastDayOfMonth = true;
                mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);

                MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger());
                mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
                mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
                if (isV12) mdTrigger.RunOnLastWeekOfMonth = true;
                mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;

                TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
                tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
                tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7);
                if (isV12) tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(19);
                if (isV12) tTrigger.Id = "Time test";
                tTrigger.Repetition.Duration = TimeSpan.FromMinutes(21);
                tTrigger.Repetition.Interval = TimeSpan.FromMinutes(17);
                tTrigger.Repetition.StopAtDurationEnd = true;

                WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger());
                wTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
                wTrigger.WeeksInterval = 3;

                // Setup Actions
                td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
                if (isV12)
                {
                    td.Actions.Context = "Author";
                    if (td.Principal.LogonType == TaskLogonType.InteractiveToken || td.Principal.LogonType == TaskLogonType.Group || td.Principal.LogonType == TaskLogonType.S4U)
                        td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
                    td.Actions.Add(new EmailAction("Testing", "*****@*****.**", "*****@*****.**", "You've got mail.", "mail.myisp.com") { Id = "Email", Attachments = new object[] { (string)new TemporaryScopedFile() } });
                    var email = (EmailAction)td.Actions["Email"];
                    email.HeaderFields.Add("Precedence", "bulk");
                    td.Actions.Add(new ComHandlerAction(new Guid("{BF300543-7BA5-4C17-A318-9BBDB7429A21}"), @"C:\Users\dahall\Documents\Visual Studio 2010\Projects\TaskHandlerProxy\TaskHandlerSample\bin\Release\TaskHandlerSample.dll|TaskHandlerSample.TaskHandler|MoreData"));
                }

                // Validate and Register task
                WriteXml(td, "PreRegTest");
                td.Validate(true);
                Task t = tf.RegisterTaskDefinition("Test", td);
                WriteXml(t);

                // Try copying it
                TaskDefinition td2 = ts.NewTask();
                foreach (Trigger tg in td.Triggers)
                    td2.Triggers.Add((Trigger)tg.Clone());
                foreach (Microsoft.Win32.TaskScheduler.Action a in td.Actions)
                    td2.Actions.Add((Microsoft.Win32.TaskScheduler.Action)a.Clone());
                tf.RegisterTaskDefinition("Test2", td2, TaskCreation.CreateOrUpdate, user, null, TaskLogonType.InteractiveToken, null);
                tf.DeleteTask("Test2");
            }
            catch (Exception ex)
            {
                output.WriteLine(ex.ToString());
                return;
            }

            // Display results
            Task runningTask = tf.Tasks["Test"];
            output.WriteLine("\nNew task will next run at " + runningTask.NextRunTime);
            DateTime[] times = runningTask.GetRunTimes(DateTime.Now, DateTime.Now + TimeSpan.FromDays(7), 0);
            if (times.Length > 0)
            {
                output.WriteLine("\nNew task will run at the following times over the next week:");
                foreach (DateTime dt in times)
                    output.WriteLine("  {0}", dt);
            }
            output.WriteLine("\nNew task triggers:");
            for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
                output.WriteLine("  {0}: {1}", i, runningTask.Definition.Triggers[i]);
            output.WriteLine("\nNew task actions:");
            for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
                output.WriteLine("  {0}: {1}", i, runningTask.Definition.Actions[i]);

            // Loop through event logs for this task and find action completed events newest to oldest
            if (isV12)
            {
                output.WriteLine("\nTask history enumeration:");
                TaskEventLog log = new TaskEventLog(@"\Maint", new int[] { 201 }, DateTime.Now.AddDays(-7)) { EnumerateInReverse = false };
                foreach (TaskEvent ev in log)
                    output.WriteLine("  Completed action '{0}' ({2}) at {1}.", ev.GetDataValue("ActionName"), ev.TimeCreated.Value, ev.GetDataValue("ResultCode"));
            }

            DisplayTask(runningTask, true);
            tf.DeleteTask("Test");
        }
예제 #3
0
 static void taskSchedule()
 {
     Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
     string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
     using (TaskService task = new TaskService())
     {
         Version version = task.HighestSupportedVersion;
         bool newVer = (version >= new Version(1, 2));
         Console.WriteLine(Resources.ResourceManager.GetString("HighestVersion" + version));
         Console.WriteLine(Resources.ResourceManager.GetString("Target"));
         Console.WriteLine(Resources.ResourceManager.GetString("RunTasks"));
         foreach (RunningTask runningTasks in task.GetRunningTasks(true))
         {
             if (runningTasks != null)
             {
                 Console.WriteLine(Resources.ResourceManager.GetString("RunPath" + runningTasks.Name + runningTasks.Path + runningTasks.State));
                 if (version.Minor > 0)
                     Console.WriteLine(Resources.ResourceManager.GetString("CurrentAction" + runningTasks.CurrentAction));
             }
         }
         TaskFolder taskFolder = task.RootFolder;
         Console.WriteLine(Resources.ResourceManager.GetString("TaskCount" + taskFolder.Tasks.Count));
         foreach (Task tasks in taskFolder.Tasks)
         {
             try
             {
                 Console.WriteLine(Resources.ResourceManager.GetString("TaskDefinition" + tasks.Name + tasks.Definition.RegistrationInfo.Author + tasks.State));
                 foreach (Trigger trigger in tasks.Definition.Triggers)
                     Console.WriteLine(Resources.ResourceManager.GetString("TaskTrigger" + trigger));
                 foreach (Microsoft.Win32.TaskScheduler.Action action in tasks.Definition.Actions)
                     Console.WriteLine(Resources.ResourceManager.GetString("TaskAction" + action));
             }
             catch (Exception)
             {
                 throw;
             }
         }
         Console.WriteLine(Resources.ResourceManager.GetString("CheckFolder"));
         TaskFolderCollection taskFolderCollection = taskFolder.SubFolders;
         if (taskFolderCollection.Count > 0)
         {
             Console.WriteLine(Resources.ResourceManager.GetString("SubFolders"));
             try
             {
                 foreach (TaskFolder standardFolder in taskFolderCollection)
                     Console.WriteLine(Resources.ResourceManager.GetString("FolderStandard" + standardFolder.Path));
             }
             catch (Exception err)
             {
                 Console.WriteLine(err.ToString());
                 throw;
             }
         }
         if (newVer)
         {
             Console.WriteLine(Resources.ResourceManager.GetString("RetrieveFolder"));
             try
             {
                 TaskFolder sub = taskFolder.SubFolders["Microsoft"];
                 Console.WriteLine(Resources.ResourceManager.GetString("SubFolderPath" + sub.Path));
             }
             catch (NotSupportedException) { }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
                 throw;
             }
         }
         Console.WriteLine(Resources.ResourceManager.GetString("CheckTask"));
         try
         {
             TaskDefinition td = task.NewTask();
             td.Principal.UserId = user;
             td.Principal.LogonType = TaskLogonType.InteractiveToken;
             td.RegistrationInfo.Author = "mikeyhalla";
             td.RegistrationInfo.Description = "Launch GClient GT Edition with Administrative rights...";
             td.Settings.Enabled = true;
             td.Settings.Priority = ProcessPriorityClass.Normal;
             td.Principal.RunLevel = TaskRunLevel.Highest;
             td.RegistrationInfo.Source = "GClientGT";
             td.RegistrationInfo.Version = new Version(0, 9);
             td.Settings.AllowDemandStart = true;
             td.Settings.Compatibility = TaskCompatibility.V2;
             LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
             if (newVer)
             {
                 lTrigger.UserId = user;
             }
             // Program to execute
             td.Actions.Add(new ExecAction("\"" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Launcher.exe" + "\"", null, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));
             taskFolder.RegisterTaskDefinition("GClientGT", td, TaskCreation.CreateOrUpdate, null, null,
                TaskLogonType.InteractiveToken, null);
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.ToString());
             throw;
         }
         Task runningTask = taskFolder.Tasks["GClientGT"];
         Console.WriteLine(Resources.ResourceManager.GetString("NextRun" + runningTask.NextRunTime));
         Console.WriteLine(Resources.ResourceManager.GetString("RunningDefinitionAction"));
         for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
             Console.WriteLine(Resources.ResourceManager.GetString("RunningDefinitionTrigger" + i + runningTask.Definition.Triggers[i]));
         Console.WriteLine(Resources.ResourceManager.GetString("NewAction"));
         for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
             Console.WriteLine(Resources.ResourceManager.GetString("RunningDefinitionAction" + i + runningTask.Definition.Actions[i]));
     }
     finalizer();
 }