/
Task.cs
3714 lines (3358 loc) · 149 KB
/
Task.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using JetBrains.Annotations;
using Microsoft.Win32.TaskScheduler.V1Interop;
using Microsoft.Win32.TaskScheduler.V2Interop;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using IPrincipal = Microsoft.Win32.TaskScheduler.V2Interop.IPrincipal;
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming ReSharper disable SuspiciousTypeConversion.Global
namespace Microsoft.Win32.TaskScheduler
{
/// <summary>Defines what versions of Task Scheduler or the AT command that the task is compatible with.</summary>
public enum TaskCompatibility
{
/// <summary>The task is compatible with the AT command.</summary>
AT,
/// <summary>
/// The task is compatible with Task Scheduler 1.0 (Windows Server™ 2003, Windows® XP, or Windows® 2000).
/// <para>Items not available when compared to V2:</para>
/// <list type="bullet">
/// <item>TaskDefinition.Principal.GroupId - All account information can be retrieved via the UserId property.</item>
/// <item>TaskLogonType values Group, None and S4U are not supported.</item>
/// <item>TaskDefinition.Principal.RunLevel == TaskRunLevel.Highest is not supported.</item>
/// <item>
/// Assigning access security to a task is not supported using TaskDefinition.RegistrationInfo.SecurityDescriptorSddlForm or in RegisterTaskDefinition.
/// </item>
/// <item>
/// TaskDefinition.RegistrationInfo.Documentation, Source, URI and Version properties are only supported using this library. See
/// details in the remarks for <see cref="TaskDefinition.Data"/>.
/// </item>
/// <item>TaskDefinition.Settings.AllowDemandStart cannot be false.</item>
/// <item>TaskDefinition.Settings.AllowHardTerminate cannot be false.</item>
/// <item>TaskDefinition.Settings.MultipleInstances can only be IgnoreNew.</item>
/// <item>TaskDefinition.Settings.NetworkSettings cannot have any values.</item>
/// <item>TaskDefinition.Settings.RestartCount can only be 0.</item>
/// <item>TaskDefinition.Settings.StartWhenAvailable can only be false.</item>
/// <item>
/// TaskDefinition.Actions can only contain ExecAction instances unless the TaskDefinition.Actions.PowerShellConversion property has
/// the Version1 flag set.
/// </item>
/// <item>TaskDefinition.Triggers cannot contain CustomTrigger, EventTrigger, SessionStateChangeTrigger, or RegistrationTrigger instances.</item>
/// <item>TaskDefinition.Triggers cannot contain instances with delays set.</item>
/// <item>TaskDefinition.Triggers cannot contain instances with ExecutionTimeLimit or Id properties set.</item>
/// <item>TaskDefinition.Triggers cannot contain LogonTriggers instances with the UserId property set.</item>
/// <item>TaskDefinition.Triggers cannot contain MonthlyDOWTrigger instances with the RunOnLastWeekOfMonth property set to <c>true</c>.</item>
/// <item>TaskDefinition.Triggers cannot contain MonthlyTrigger instances with the RunOnDayWeekOfMonth property set to <c>true</c>.</item>
/// </list>
/// </summary>
V1,
/// <summary>
/// The task is compatible with Task Scheduler 2.0 (Windows Vista™, Windows Server™ 2008).
/// <para>
/// This version is the baseline for the new, non-file based Task Scheduler. See <see cref="TaskCompatibility.V1"/> remarks for
/// functionality that was not forward-compatible.
/// </para>
/// </summary>
V2,
/// <summary>
/// The task is compatible with Task Scheduler 2.1 (Windows® 7, Windows Server™ 2008 R2).
/// <para>Changes from V2:</para>
/// <list type="bullet">
/// <item>TaskDefinition.Principal.ProcessTokenSidType can be defined as a value other than Default.</item>
/// <item>
/// TaskDefinition.Actions may not contain EmailAction or ShowMessageAction instances unless the
/// TaskDefinition.Actions.PowerShellConversion property has the Version2 flag set.
/// </item>
/// <item>TaskDefinition.Principal.RequiredPrivileges can have privilege values assigned.</item>
/// <item>TaskDefinition.Settings.DisallowStartOnRemoteAppSession can be set to true.</item>
/// <item>TaskDefinition.UseUnifiedSchedulingEngine can be set to true.</item>
/// </list>
/// </summary>
V2_1,
/// <summary>
/// The task is compatible with Task Scheduler 2.2 (Windows® 8.x, Windows Server™ 2012).
/// <para>Changes from V2_1:</para>
/// <list type="bullet">
/// <item>
/// TaskDefinition.Settings.MaintenanceSettings can have Period or Deadline be values other than TimeSpan.Zero or the Exclusive
/// property set to true.
/// </item>
/// <item>TaskDefinition.Settings.Volatile can be set to true.</item>
/// </list>
/// </summary>
V2_2,
/// <summary>
/// The task is compatible with Task Scheduler 2.3 (Windows® 10, Windows Server™ 2016).
/// <para>Changes from V2_2:</para>
/// <list type="bullet">
/// <item>None published.</item>
/// </list>
/// </summary>
V2_3
}
/// <summary>Defines how the Task Scheduler service creates, updates, or disables the task.</summary>
[DefaultValue(CreateOrUpdate)]
public enum TaskCreation
{
/// <summary>The Task Scheduler service registers the task as a new task.</summary>
Create = 2,
/// <summary>
/// The Task Scheduler service either registers the task as a new task or as an updated version if the task already exists.
/// Equivalent to Create | Update.
/// </summary>
CreateOrUpdate = 6,
/// <summary>
/// The Task Scheduler service registers the disabled task. A disabled task cannot run until it is enabled. For more information,
/// see Enabled Property of TaskSettings and Enabled Property of RegisteredTask.
/// </summary>
Disable = 8,
/// <summary>
/// The Task Scheduler service is prevented from adding the allow access-control entry (ACE) for the context principal. When the
/// TaskFolder.RegisterTaskDefinition or TaskFolder.RegisterTask functions are called with this flag to update a task, the Task
/// Scheduler service does not add the ACE for the new context principal and does not remove the ACE from the old context principal.
/// </summary>
DontAddPrincipalAce = 0x10,
/// <summary>
/// The Task Scheduler service creates the task, but ignores the registration triggers in the task. By ignoring the registration
/// triggers, the task will not execute when it is registered unless a time-based trigger causes it to execute on registration.
/// </summary>
IgnoreRegistrationTriggers = 0x20,
/// <summary>
/// The Task Scheduler service registers the task as an updated version of an existing task. When a task with a registration trigger
/// is updated, the task will execute after the update occurs.
/// </summary>
Update = 4,
/// <summary>
/// The Task Scheduler service checks the syntax of the XML that describes the task but does not register the task. This constant
/// cannot be combined with the Create, Update, or CreateOrUpdate values.
/// </summary>
ValidateOnly = 1
}
/// <summary>Defines how the Task Scheduler handles existing instances of the task when it starts a new instance of the task.</summary>
[DefaultValue(IgnoreNew)]
public enum TaskInstancesPolicy
{
/// <summary>Starts new instance while an existing instance is running.</summary>
Parallel,
/// <summary>Starts a new instance of the task after all other instances of the task are complete.</summary>
Queue,
/// <summary>Does not start a new instance if an existing instance of the task is running.</summary>
IgnoreNew,
/// <summary>Stops an existing instance of the task before it starts a new instance.</summary>
StopExisting
}
/// <summary>Defines what logon technique is required to run a task.</summary>
[DefaultValue(S4U)]
public enum TaskLogonType
{
/// <summary>The logon method is not specified. Used for non-NT credentials.</summary>
None,
/// <summary>Use a password for logging on the user. The password must be supplied at registration time.</summary>
Password,
/// <summary>
/// Use an existing interactive token to run a task. The user must log on using a service for user (S4U) logon. When an S4U logon is
/// used, no password is stored by the system and there is no access to either the network or to encrypted files.
/// </summary>
S4U,
/// <summary>User must already be logged on. The task will be run only in an existing interactive session.</summary>
InteractiveToken,
/// <summary>Group activation. The groupId field specifies the group.</summary>
Group,
/// <summary>
/// Indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task.
/// </summary>
ServiceAccount,
/// <summary>
/// First use the interactive token. If the user is not logged on (no interactive token is available), then the password is used.
/// The password must be specified when a task is registered. This flag is not recommended for new tasks because it is less reliable
/// than Password.
/// </summary>
InteractiveTokenOrPassword
}
/// <summary>Defines which privileges must be required for a secured task.</summary>
public enum TaskPrincipalPrivilege
{
/// <summary>Required to create a primary token. User Right: Create a token object.</summary>
SeCreateTokenPrivilege = 1,
/// <summary>Required to assign the primary token of a process. User Right: Replace a process-level token.</summary>
SeAssignPrimaryTokenPrivilege,
/// <summary>Required to lock physical pages in memory. User Right: Lock pages in memory.</summary>
SeLockMemoryPrivilege,
/// <summary>Required to increase the quota assigned to a process. User Right: Adjust memory quotas for a process.</summary>
SeIncreaseQuotaPrivilege,
/// <summary>Required to read unsolicited input from a terminal device. User Right: Not applicable.</summary>
SeUnsolicitedInputPrivilege,
/// <summary>Required to create a computer account. User Right: Add workstations to domain.</summary>
SeMachineAccountPrivilege,
/// <summary>
/// This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this
/// privilege. User Right: Act as part of the operating system.
/// </summary>
SeTcbPrivilege,
/// <summary>
/// Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege
/// identifies its holder as a security operator. User Right: Manage auditing and the security log.
/// </summary>
SeSecurityPrivilege,
/// <summary>
/// Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be
/// set only to those values that the holder may legitimately assign as the owner of an object. User Right: Take ownership of files
/// or other objects.
/// </summary>
SeTakeOwnershipPrivilege,
/// <summary>Required to load or unload a device driver. User Right: Load and unload device drivers.</summary>
SeLoadDriverPrivilege,
/// <summary>Required to gather profiling information for the entire system. User Right: Profile system performance.</summary>
SeSystemProfilePrivilege,
/// <summary>Required to modify the system time. User Right: Change the system time.</summary>
SeSystemtimePrivilege,
/// <summary>Required to gather profiling information for a single process. User Right: Profile single process.</summary>
SeProfileSingleProcessPrivilege,
/// <summary>Required to increase the base priority of a process. User Right: Increase scheduling priority.</summary>
SeIncreaseBasePriorityPrivilege,
/// <summary>Required to create a paging file. User Right: Create a pagefile.</summary>
SeCreatePagefilePrivilege,
/// <summary>Required to create a permanent object. User Right: Create permanent shared objects.</summary>
SeCreatePermanentPrivilege,
/// <summary>
/// Required to perform backup operations. This privilege causes the system to grant all read access control to any file, regardless
/// of the access control list (ACL) specified for the file. Any access request other than read is still evaluated with the ACL.
/// This privilege is required by the RegSaveKey and RegSaveKeyExfunctions. The following access rights are granted if this
/// privilege is held: READ_CONTROL, ACCESS_SYSTEM_SECURITY, FILE_GENERIC_READ, FILE_TRAVERSE. User Right: Back up files and directories.
/// </summary>
SeBackupPrivilege,
/// <summary>
/// Required to perform restore operations. This privilege causes the system to grant all write access control to any file,
/// regardless of the ACL specified for the file. Any access request other than write is still evaluated with the ACL. Additionally,
/// this privilege enables you to set any valid user or group security identifier (SID) as the owner of a file. This privilege is
/// required by the RegLoadKey function. The following access rights are granted if this privilege is held: WRITE_DAC, WRITE_OWNER,
/// ACCESS_SYSTEM_SECURITY, FILE_GENERIC_WRITE, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, DELETE. User Right: Restore files and directories.
/// </summary>
SeRestorePrivilege,
/// <summary>Required to shut down a local system. User Right: Shut down the system.</summary>
SeShutdownPrivilege,
/// <summary>Required to debug and adjust the memory of a process owned by another account. User Right: Debug programs.</summary>
SeDebugPrivilege,
/// <summary>Required to generate audit-log entries. Give this privilege to secure servers. User Right: Generate security audits.</summary>
SeAuditPrivilege,
/// <summary>
/// Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information. User Right:
/// Modify firmware environment values.
/// </summary>
SeSystemEnvironmentPrivilege,
/// <summary>
/// Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all
/// traversal access checks. It is enabled by default for all users. User Right: Bypass traverse checking.
/// </summary>
SeChangeNotifyPrivilege,
/// <summary>Required to shut down a system by using a network request. User Right: Force shutdown from a remote system.</summary>
SeRemoteShutdownPrivilege,
/// <summary>Required to undock a laptop. User Right: Remove computer from docking station.</summary>
SeUndockPrivilege,
/// <summary>
/// Required for a domain controller to use the LDAP directory synchronization services. This privilege allows the holder to read
/// all objects and properties in the directory, regardless of the protection on the objects and properties. By default, it is
/// assigned to the Administrator and LocalSystem accounts on domain controllers. User Right: Synchronize directory service data.
/// </summary>
SeSyncAgentPrivilege,
/// <summary>
/// Required to mark user and computer accounts as trusted for delegation. User Right: Enable computer and user accounts to be
/// trusted for delegation.
/// </summary>
SeEnableDelegationPrivilege,
/// <summary>Required to enable volume management privileges. User Right: Manage the files on a volume.</summary>
SeManageVolumePrivilege,
/// <summary>
/// Required to impersonate. User Right: Impersonate a client after authentication. Windows XP/2000: This privilege is not
/// supported. Note that this value is supported starting with Windows Server 2003, Windows XP with SP2, and Windows 2000 with SP4.
/// </summary>
SeImpersonatePrivilege,
/// <summary>
/// Required to create named file mapping objects in the global namespace during Terminal Services sessions. This privilege is
/// enabled by default for administrators, services, and the local system account. User Right: Create global objects. Windows
/// XP/2000: This privilege is not supported. Note that this value is supported starting with Windows Server 2003, Windows XP with
/// SP2, and Windows 2000 with SP4.
/// </summary>
SeCreateGlobalPrivilege,
/// <summary>Required to access Credential Manager as a trusted caller. User Right: Access Credential Manager as a trusted caller.</summary>
SeTrustedCredManAccessPrivilege,
/// <summary>Required to modify the mandatory integrity level of an object. User Right: Modify an object label.</summary>
SeRelabelPrivilege,
/// <summary>
/// Required to allocate more memory for applications that run in the context of users. User Right: Increase a process working set.
/// </summary>
SeIncreaseWorkingSetPrivilege,
/// <summary>Required to adjust the time zone associated with the computer's internal clock. User Right: Change the time zone.</summary>
SeTimeZonePrivilege,
/// <summary>Required to create a symbolic link. User Right: Create symbolic links.</summary>
SeCreateSymbolicLinkPrivilege
}
/// <summary>
/// Defines the types of process security identifier (SID) that can be used by tasks. These changes are used to specify the type of
/// process SID in the IPrincipal2 interface.
/// </summary>
public enum TaskProcessTokenSidType
{
/// <summary>No changes will be made to the process token groups list.</summary>
None = 0,
/// <summary>
/// A task SID that is derived from the task name will be added to the process token groups list, and the token default
/// discretionary access control list (DACL) will be modified to allow only the task SID and local system full control and the
/// account SID read control.
/// </summary>
Unrestricted = 1,
/// <summary>A Task Scheduler will apply default settings to the task process.</summary>
Default = 2
}
/// <summary>Defines how a task is run.</summary>
[Flags]
public enum TaskRunFlags
{
/// <summary>The task is run with all flags ignored.</summary>
NoFlags = 0,
/// <summary>The task is run as the user who is calling the Run method.</summary>
AsSelf = 1,
/// <summary>The task is run regardless of constraints such as "do not run on batteries" or "run only if idle".</summary>
IgnoreConstraints = 2,
/// <summary>The task is run using a terminal server session identifier.</summary>
UseSessionId = 4,
/// <summary>The task is run using a security identifier.</summary>
UserSID = 8
}
/// <summary>Defines LUA elevation flags that specify with what privilege level the task will be run.</summary>
public enum TaskRunLevel
{
/// <summary>Tasks will be run with the least privileges.</summary>
[XmlEnum("LeastPrivilege")]
LUA,
/// <summary>Tasks will be run with the highest privileges.</summary>
[XmlEnum("HighestAvailable")]
Highest
}
/// <summary>
/// Defines what kind of Terminal Server session state change you can use to trigger a task to start. These changes are used to specify
/// the type of state change in the SessionStateChangeTrigger.
/// </summary>
public enum TaskSessionStateChangeType
{
/// <summary>
/// Terminal Server console connection state change. For example, when you connect to a user session on the local computer by
/// switching users on the computer.
/// </summary>
ConsoleConnect = 1,
/// <summary>
/// Terminal Server console disconnection state change. For example, when you disconnect to a user session on the local computer by
/// switching users on the computer.
/// </summary>
ConsoleDisconnect = 2,
/// <summary>
/// Terminal Server remote connection state change. For example, when a user connects to a user session by using the Remote Desktop
/// Connection program from a remote computer.
/// </summary>
RemoteConnect = 3,
/// <summary>
/// Terminal Server remote disconnection state change. For example, when a user disconnects from a user session while using the
/// Remote Desktop Connection program from a remote computer.
/// </summary>
RemoteDisconnect = 4,
/// <summary>
/// Terminal Server session locked state change. For example, this state change causes the task to run when the computer is locked.
/// </summary>
SessionLock = 7,
/// <summary>
/// Terminal Server session unlocked state change. For example, this state change causes the task to run when the computer is unlocked.
/// </summary>
SessionUnlock = 8
}
/// <summary>Options for use when calling the SetSecurityDescriptorSddlForm methods.</summary>
[Flags]
public enum TaskSetSecurityOptions
{
/// <summary>No special handling.</summary>
None = 0,
/// <summary>The Task Scheduler service is prevented from adding the allow access-control entry (ACE) for the context principal.</summary>
DontAddPrincipalAce = 0x10
}
/***** WAITING TO DETERMINE USE CASE *****
/// <summary>Success and error codes that some methods will expose through <see cref="COMExcpetion"/>.</summary>
public enum TaskResultCode
{
/// <summary>The task is ready to run at its next scheduled time.</summary>
TaskReady = 0x00041300,
/// <summary>The task is currently running.</summary>
TaskRunning = 0x00041301,
/// <summary>The task will not run at the scheduled times because it has been disabled.</summary>
TaskDisabled = 0x00041302,
/// <summary>The task has not yet run.</summary>
TaskHasNotRun = 0x00041303,
/// <summary>There are no more runs scheduled for this task.</summary>
TaskNoMoreRuns = 0x00041304,
/// <summary>One or more of the properties that are needed to run this task on a schedule have not been set.</summary>
TaskNotScheduled = 0x00041305,
/// <summary>The last run of the task was terminated by the user.</summary>
TaskTerminated = 0x00041306,
/// <summary>Either the task has no triggers or the existing triggers are disabled or not set.</summary>
TaskNoValidTriggers = 0x00041307,
/// <summary>Event triggers do not have set run times.</summary>
EventTrigger = 0x00041308,
/// <summary>A task's trigger is not found.</summary>
TriggerNotFound = 0x80041309,
/// <summary>One or more of the properties required to run this task have not been set.</summary>
TaskNotReady = 0x8004130A,
/// <summary>There is no running instance of the task.</summary>
TaskNotRunning = 0x8004130B,
/// <summary>The Task Scheduler service is not installed on this computer.</summary>
ServiceNotInstalled = 0x8004130C,
/// <summary>The task object could not be opened.</summary>
CannotOpenTask = 0x8004130D,
/// <summary>The object is either an invalid task object or is not a task object.</summary>
InvalidTask = 0x8004130E,
/// <summary>No account information could be found in the Task Scheduler security database for the task indicated.</summary>
AccountInformationNotSet = 0x8004130F,
/// <summary>Unable to establish existence of the account specified.</summary>
AccountNameNotFound = 0x80041310,
/// <summary>Corruption was detected in the Task Scheduler security database; the database has been reset.</summary>
AccountDbaseCorrupt = 0x80041311,
/// <summary>Task Scheduler security services are available only on Windows NT.</summary>
NoSecurityServices = 0x80041312,
/// <summary>The task object version is either unsupported or invalid.</summary>
UnknownObjectVersion = 0x80041313,
/// <summary>The task has been configured with an unsupported combination of account settings and run time options.</summary>
UnsupportedAccountOption = 0x80041314,
/// <summary>The Task Scheduler Service is not running.</summary>
ServiceNotRunning = 0x80041315,
/// <summary>The task XML contains an unexpected node.</summary>
UnexpectedNode = 0x80041316,
/// <summary>The task XML contains an element or attribute from an unexpected namespace.</summary>
Namespace = 0x80041317,
/// <summary>The task XML contains a value which is incorrectly formatted or out of range.</summary>
InvalidValue = 0x80041318,
/// <summary>The task XML is missing a required element or attribute.</summary>
MissingNode = 0x80041319,
/// <summary>The task XML is malformed.</summary>
MalformedXml = 0x8004131A,
/// <summary>The task is registered, but not all specified triggers will start the task.</summary>
SomeTriggersFailed = 0x0004131B,
/// <summary>The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal.</summary>
BatchLogonProblem = 0x0004131C,
/// <summary>The task XML contains too many nodes of the same type.</summary>
TooManyNodes = 0x8004131D,
/// <summary>The task cannot be started after the trigger end boundary.</summary>
PastEndBoundary = 0x8004131E,
/// <summary>An instance of this task is already running.</summary>
AlreadyRunning = 0x8004131F,
/// <summary>The task will not run because the user is not logged on.</summary>
UserNotLoggedOn = 0x80041320,
/// <summary>The task image is corrupt or has been tampered with.</summary>
InvalidTaskHash = 0x80041321,
/// <summary>The Task Scheduler service is not available.</summary>
ServiceNotAvailable = 0x80041322,
/// <summary>The Task Scheduler service is too busy to handle your request. Please try again later.</summary>
ServiceTooBusy = 0x80041323,
/// <summary>
/// The Task Scheduler service attempted to run the task, but the task did not run due to one of the constraints in the task definition.
/// </summary>
TaskAttempted = 0x80041324,
/// <summary>The Task Scheduler service has asked the task to run.</summary>
TaskQueued = 0x00041325,
/// <summary>The task is disabled.</summary>
TaskDisabled = 0x80041326,
/// <summary>The task has properties that are not compatible with earlier versions of Windows.</summary>
TaskNotV1Compatible = 0x80041327,
/// <summary>The task settings do not allow the task to start on demand.</summary>
StartOnDemand = 0x80041328,
}
*/
/// <summary>Defines the different states that a registered task can be in.</summary>
public enum TaskState
{
/// <summary>The state of the task is unknown.</summary>
Unknown,
/// <summary>
/// The task is registered but is disabled and no instances of the task are queued or running. The task cannot be run until it is enabled.
/// </summary>
Disabled,
/// <summary>Instances of the task are queued.</summary>
Queued,
/// <summary>The task is ready to be executed, but no instances are queued or running.</summary>
Ready,
/// <summary>One or more instances of the task is running.</summary>
Running
}
/// <summary>
/// Specifies how the Task Scheduler performs tasks when the computer is in an idle condition. For information about idle conditions,
/// see Task Idle Conditions.
/// </summary>
[PublicAPI]
public sealed class IdleSettings : IDisposable, INotifyPropertyChanged
{
private readonly IIdleSettings v2Settings;
private ITask v1Task;
internal IdleSettings([NotNull] IIdleSettings iSettings) => v2Settings = iSettings;
internal IdleSettings([NotNull] ITask iTask) => v1Task = iTask;
/// <summary>Occurs when a property value changes.</summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets or sets a value that indicates the amount of time that the computer must be in an idle state before the task is run.
/// </summary>
/// <value>
/// A value that indicates the amount of time that the computer must be in an idle state before the task is run. The minimum value
/// is one minute. If this value is <c>TimeSpan.Zero</c>, then the delay will be set to the default of 10 minutes.
/// </value>
[DefaultValue(typeof(TimeSpan), "00:10:00")]
[XmlElement("Duration")]
public TimeSpan IdleDuration
{
get
{
if (v2Settings != null)
return Task.StringToTimeSpan(v2Settings.IdleDuration);
v1Task.GetIdleWait(out var _, out var deadMin);
return TimeSpan.FromMinutes(deadMin);
}
set
{
if (v2Settings != null)
{
if (value != TimeSpan.Zero && value < TimeSpan.FromMinutes(1))
throw new ArgumentOutOfRangeException(nameof(IdleDuration));
v2Settings.IdleDuration = Task.TimeSpanToString(value);
}
else
{
v1Task.SetIdleWait((ushort)WaitTimeout.TotalMinutes, (ushort)value.TotalMinutes);
}
OnNotifyPropertyChanged();
}
}
/// <summary>
/// Gets or sets a Boolean value that indicates whether the task is restarted when the computer cycles into an idle condition more
/// than once.
/// </summary>
[DefaultValue(false)]
public bool RestartOnIdle
{
get => v2Settings?.RestartOnIdle ?? v1Task.HasFlags(TaskFlags.RestartOnIdleResume);
set
{
if (v2Settings != null)
v2Settings.RestartOnIdle = value;
else
v1Task.SetFlags(TaskFlags.RestartOnIdleResume, value);
OnNotifyPropertyChanged();
}
}
/// <summary>
/// Gets or sets a Boolean value that indicates that the Task Scheduler will terminate the task if the idle condition ends before
/// the task is completed.
/// </summary>
[DefaultValue(true)]
public bool StopOnIdleEnd
{
get => v2Settings?.StopOnIdleEnd ?? v1Task.HasFlags(TaskFlags.KillOnIdleEnd);
set
{
if (v2Settings != null)
v2Settings.StopOnIdleEnd = value;
else
v1Task.SetFlags(TaskFlags.KillOnIdleEnd, value);
OnNotifyPropertyChanged();
}
}
/// <summary>
/// Gets or sets a value that indicates the amount of time that the Task Scheduler will wait for an idle condition to occur. If no
/// value is specified for this property, then the Task Scheduler service will wait indefinitely for an idle condition to occur.
/// </summary>
/// <value>
/// A value that indicates the amount of time that the Task Scheduler will wait for an idle condition to occur. The minimum time
/// allowed is 1 minute. If this value is <c>TimeSpan.Zero</c>, then the delay will be the equivalent of "Do not wait".
/// </value>
[DefaultValue(typeof(TimeSpan), "01:00:00")]
public TimeSpan WaitTimeout
{
get
{
if (v2Settings != null)
return Task.StringToTimeSpan(v2Settings.WaitTimeout);
v1Task.GetIdleWait(out var idleMin, out var _);
return TimeSpan.FromMinutes(idleMin);
}
set
{
if (v2Settings != null)
{
if (value != TimeSpan.Zero && value < TimeSpan.FromMinutes(1))
throw new ArgumentOutOfRangeException(nameof(WaitTimeout));
v2Settings.WaitTimeout = value == TimeSpan.Zero ? "PT0S" : Task.TimeSpanToString(value);
}
else
{
v1Task.SetIdleWait((ushort)value.TotalMinutes, (ushort)IdleDuration.TotalMinutes);
}
OnNotifyPropertyChanged();
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Settings != null)
Marshal.ReleaseComObject(v2Settings);
v1Task = null;
}
/// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString()
{
if (v2Settings != null || v1Task != null)
return DebugHelper.GetDebugString(this);
return base.ToString();
}
/// <summary>Called when a property has changed to notify any attached elements.</summary>
/// <param name="propertyName">Name of the property.</param>
private void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>Specifies the task settings the Task scheduler will use to start task during Automatic maintenance.</summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public sealed class MaintenanceSettings : IDisposable, INotifyPropertyChanged
{
private readonly ITaskSettings3 iSettings;
private IMaintenanceSettings iMaintSettings;
internal MaintenanceSettings([CanBeNull] ITaskSettings3 iSettings3)
{
iSettings = iSettings3;
if (iSettings3 != null)
iMaintSettings = iSettings.MaintenanceSettings;
}
/// <summary>Occurs when a property value changes.</summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets or sets the amount of time after which the Task scheduler attempts to run the task during emergency Automatic maintenance,
/// if the task failed to complete during regular Automatic maintenance. The minimum value is one day. The value of the <see
/// cref="Deadline"/> property should be greater than the value of the <see cref="Period"/> property. If the deadline is not
/// specified the task will not be started during emergency Automatic maintenance.
/// </summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(typeof(TimeSpan), "00:00:00")]
public TimeSpan Deadline
{
get => iMaintSettings != null ? Task.StringToTimeSpan(iMaintSettings.Deadline) : TimeSpan.Zero;
set
{
if (iSettings != null)
{
if (iMaintSettings == null && value != TimeSpan.Zero)
iMaintSettings = iSettings.CreateMaintenanceSettings();
if (iMaintSettings != null)
iMaintSettings.Deadline = Task.TimeSpanToString(value);
}
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
OnNotifyPropertyChanged();
}
}
/// <summary>
/// Gets or sets a value indicating whether the Task Scheduler must start the task during the Automatic maintenance in exclusive
/// mode. The exclusivity is guaranteed only between other maintenance tasks and doesn't grant any ordering priority of the task. If
/// exclusivity is not specified, the task is started in parallel with other maintenance tasks.
/// </summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(false)]
public bool Exclusive
{
get => iMaintSettings != null && iMaintSettings.Exclusive;
set
{
if (iSettings != null)
{
if (iMaintSettings == null && value)
iMaintSettings = iSettings.CreateMaintenanceSettings();
if (iMaintSettings != null)
iMaintSettings.Exclusive = value;
}
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
OnNotifyPropertyChanged();
}
}
/// <summary>
/// Gets or sets the amount of time the task needs to be started during Automatic maintenance. The minimum value is one minute.
/// </summary>
/// <exception cref="NotSupportedPriorToException">Property set for a task on a Task Scheduler version prior to 2.2.</exception>
[DefaultValue(typeof(TimeSpan), "00:00:00")]
public TimeSpan Period
{
get => iMaintSettings != null ? Task.StringToTimeSpan(iMaintSettings.Period) : TimeSpan.Zero;
set
{
if (iSettings != null)
{
if (iMaintSettings == null && value != TimeSpan.Zero)
iMaintSettings = iSettings.CreateMaintenanceSettings();
if (iMaintSettings != null)
iMaintSettings.Period = Task.TimeSpanToString(value);
}
else
throw new NotSupportedPriorToException(TaskCompatibility.V2_2);
OnNotifyPropertyChanged();
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (iMaintSettings != null)
Marshal.ReleaseComObject(iMaintSettings);
}
/// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString() => iMaintSettings != null ? DebugHelper.GetDebugString(this) : base.ToString();
internal bool IsSet() => iMaintSettings != null && (iMaintSettings.Period != null || iMaintSettings.Deadline != null || iMaintSettings.Exclusive);
/// <summary>Called when a property has changed to notify any attached elements.</summary>
/// <param name="propertyName">Name of the property.</param>
private void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>Provides the settings that the Task Scheduler service uses to obtain a network profile.</summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public sealed class NetworkSettings : IDisposable, INotifyPropertyChanged
{
private readonly INetworkSettings v2Settings;
internal NetworkSettings([CanBeNull] INetworkSettings iSettings) => v2Settings = iSettings;
/// <summary>Occurs when a property value changes.</summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>Gets or sets a GUID value that identifies a network profile.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(typeof(Guid), "00000000-0000-0000-0000-000000000000")]
public Guid Id
{
get
{
string id = null;
if (v2Settings != null)
id = v2Settings.Id;
return string.IsNullOrEmpty(id) ? Guid.Empty : new Guid(id);
}
set
{
if (v2Settings != null)
v2Settings.Id = value == Guid.Empty ? null : value.ToString();
else
throw new NotV1SupportedException();
OnNotifyPropertyChanged();
}
}
/// <summary>Gets or sets the name of a network profile. The name is used for display purposes.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
[DefaultValue(null)]
public string Name
{
get => v2Settings?.Name;
set
{
if (v2Settings != null)
v2Settings.Name = value;
else
throw new NotV1SupportedException();
OnNotifyPropertyChanged();
}
}
/// <summary>Releases all resources used by this class.</summary>
public void Dispose()
{
if (v2Settings != null)
Marshal.ReleaseComObject(v2Settings);
}
/// <summary>Returns a <see cref="string"/> that represents this instance.</summary>
/// <returns>A <see cref="string"/> that represents this instance.</returns>
public override string ToString()
{
if (v2Settings != null)
return DebugHelper.GetDebugString(this);
return base.ToString();
}
internal bool IsSet() => v2Settings != null && (!string.IsNullOrEmpty(v2Settings.Id) || !string.IsNullOrEmpty(v2Settings.Name));
/// <summary>Called when a property has changed to notify any attached elements.</summary>
/// <param name="propertyName">Name of the property.</param>
private void OnNotifyPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>Provides the methods to get information from and control a running task.</summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public sealed class RunningTask : Task
{
private readonly IRunningTask v2RunningTask;
internal RunningTask([NotNull] TaskService svc, [NotNull] IRegisteredTask iTask, [NotNull] IRunningTask iRunningTask)
: base(svc, iTask) => v2RunningTask = iRunningTask;
internal RunningTask([NotNull] TaskService svc, [NotNull] ITask iTask)
: base(svc, iTask)
{
}
/// <summary>Gets the process ID for the engine (process) which is running the task.</summary>
/// <exception cref="NotV1SupportedException">Not supported under Task Scheduler 1.0.</exception>
public uint EnginePID
{
get
{
if (v2RunningTask != null)
return v2RunningTask.EnginePID;
throw new NotV1SupportedException();
}
}
/// <summary>Gets the name of the current action that the running task is performing.</summary>
public string CurrentAction => v2RunningTask != null ? v2RunningTask.CurrentAction : v1Task.GetApplicationName();
/// <summary>Gets the GUID identifier for this instance of the task.</summary>
public Guid InstanceGuid => v2RunningTask != null ? new Guid(v2RunningTask.InstanceGuid) : Guid.Empty;
/// <summary>Gets the operational state of the running task.</summary>
public override TaskState State => v2RunningTask?.State ?? base.State;
/// <summary>Releases all resources used by this class.</summary>
public new void Dispose()
{
base.Dispose();
if (v2RunningTask != null) Marshal.ReleaseComObject(v2RunningTask);
}
/// <summary>Refreshes all of the local instance variables of the task.</summary>
/// <exception cref="InvalidOperationException">Thrown if task is no longer running.</exception>
public void Refresh()
{
try { v2RunningTask?.Refresh(); }
catch (COMException ce) when ((uint)ce.ErrorCode == 0x8004130B)
{
throw new InvalidOperationException("The current task is no longer running.", ce);
}
}
}
/// <summary>
/// Provides the methods that are used to run the task immediately, get any running instances of the task, get or set the credentials
/// that are used to register the task, and the properties that describe the task.
/// </summary>
[XmlType(IncludeInSchema = false)]
[PublicAPI]
public class Task : IDisposable, IComparable, IComparable<Task>, INotifyPropertyChanged
{
internal const AccessControlSections defaultAccessControlSections = AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access;
internal const SecurityInfos defaultSecurityInfosSections = SecurityInfos.Owner | SecurityInfos.Group | SecurityInfos.DiscretionaryAcl;
internal ITask v1Task;
private static readonly int osLibMinorVer = GetOSLibraryMinorVersion();
private static readonly DateTime v2InvalidDate = new DateTime(1899, 12, 30);
private readonly IRegisteredTask v2Task;
private TaskDefinition myTD;
internal Task([NotNull] TaskService svc, [NotNull] ITask iTask)
{
TaskService = svc;
v1Task = iTask;
ReadOnly = false;
}
internal Task([NotNull] TaskService svc, [NotNull] IRegisteredTask iTask, ITaskDefinition iDef = null)
{
TaskService = svc;
v2Task = iTask;
if (iDef != null)
myTD = new TaskDefinition(iDef);
ReadOnly = false;
}