win task scheduler

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa383608(v=vs.85).aspx
"""
Windows Task Scheduler Module
.. versionadded:: 2016.3.0
A module for working with the Windows Task Scheduler.
You can add and edit existing tasks.
You can add and clear triggers and actions.
You can list all tasks, folders, triggers, and actions.
"""
 
import logging
import time
from datetime import datetime
 
import salt.utils.platform
import salt.utils.winapi
from salt.exceptions import ArgumentValueError, CommandExecutionError
 
try:
    import pythoncom
    import win32com.client
 
    HAS_DEPENDENCIES = True
except ImportError:
    HAS_DEPENDENCIES = False
 
log = logging.getLogger(__name__)
 
# Define the module's virtual name
__virtualname__ = "task"
 
# Define Constants
# TASK_ACTION_TYPE
TASK_ACTION_EXEC = 0
TASK_ACTION_COM_HANDLER = 5
TASK_ACTION_SEND_EMAIL = 6
TASK_ACTION_SHOW_MESSAGE = 7
 
# TASK_COMPATIBILITY
TASK_COMPATIBILITY_AT = 0
TASK_COMPATIBILITY_V1 = 1
TASK_COMPATIBILITY_V2 = 2
TASK_COMPATIBILITY_V3 = 3
 
# TASK_CREATION
TASK_VALIDATE_ONLY = 0x1
TASK_CREATE = 0x2
TASK_UPDATE = 0x4
TASK_CREATE_OR_UPDATE = 0x6
TASK_DISABLE = 0x8
TASK_DONT_ADD_PRINCIPAL_ACE = 0x10
TASK_IGNORE_REGISTRATION_TRIGGERS = 0x20
 
# TASK_INSTANCES_POLICY
TASK_INSTANCES_PARALLEL = 0
TASK_INSTANCES_QUEUE = 1
TASK_INSTANCES_IGNORE_NEW = 2
TASK_INSTANCES_STOP_EXISTING = 3
 
# TASK_LOGON_TYPE
TASK_LOGON_NONE = 0
TASK_LOGON_PASSWORD = 1
TASK_LOGON_S4U = 2
TASK_LOGON_INTERACTIVE_TOKEN = 3
TASK_LOGON_GROUP = 4
TASK_LOGON_SERVICE_ACCOUNT = 5
TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD = 6
 
# TASK_RUNLEVEL_TYPE
TASK_RUNLEVEL_LUA = 0
TASK_RUNLEVEL_HIGHEST = 1
 
# TASK_STATE_TYPE
TASK_STATE_UNKNOWN = 0
TASK_STATE_DISABLED = 1
TASK_STATE_QUEUED = 2
TASK_STATE_READY = 3
TASK_STATE_RUNNING = 4
 
# TASK_TRIGGER_TYPE
TASK_TRIGGER_EVENT = 0
TASK_TRIGGER_TIME = 1
TASK_TRIGGER_DAILY = 2
TASK_TRIGGER_WEEKLY = 3
TASK_TRIGGER_MONTHLY = 4
TASK_TRIGGER_MONTHLYDOW = 5
TASK_TRIGGER_IDLE = 6
TASK_TRIGGER_REGISTRATION = 7
TASK_TRIGGER_BOOT = 8
TASK_TRIGGER_LOGON = 9
TASK_TRIGGER_SESSION_STATE_CHANGE = 11
 
duration = {
    "Immediately": "PT0M",
    "Indefinitely": "",
    "Do not wait": "PT0M",
    "15 seconds": "PT15S",
    "30 seconds": "PT30S",
    "1 minute": "PT1M",
    "5 minutes": "PT5M",
    "10 minutes": "PT10M",
    "15 minutes": "PT15M",
    "30 minutes": "PT30M",
    "1 hour": "PT1H",
    "2 hours": "PT2H",
    "4 hours": "PT4H",
    "8 hours": "PT8H",
    "12 hours": "PT12H",
    "1 day": ["P1D", "PT24H"],
    "3 days": ["P3D", "PT72H"],
    "30 days": "P30D",
    "90 days": "P90D",
    "180 days": "P180D",
    "365 days": "P365D",
}
 
action_types = {
    "Execute": TASK_ACTION_EXEC,
    "Email": TASK_ACTION_SEND_EMAIL,
    "Message": TASK_ACTION_SHOW_MESSAGE,
}
 
trigger_types = {
    "Event": TASK_TRIGGER_EVENT,
    "Once": TASK_TRIGGER_TIME,
    "Daily": TASK_TRIGGER_DAILY,
    "Weekly": TASK_TRIGGER_WEEKLY,
    "Monthly": TASK_TRIGGER_MONTHLY,
    "MonthlyDay": TASK_TRIGGER_MONTHLYDOW,
    "OnIdle": TASK_TRIGGER_IDLE,
    "OnTaskCreation": TASK_TRIGGER_REGISTRATION,
    "OnBoot": TASK_TRIGGER_BOOT,
    "OnLogon": TASK_TRIGGER_LOGON,
    "OnSessionChange": TASK_TRIGGER_SESSION_STATE_CHANGE,
}
 
states = {
    TASK_STATE_UNKNOWN: "Unknown",
    TASK_STATE_DISABLED: "Disabled",
    TASK_STATE_QUEUED: "Queued",
    TASK_STATE_READY: "Ready",
    TASK_STATE_RUNNING: "Running",
}
 
instances = {
    "Parallel": TASK_INSTANCES_PARALLEL,
    "Queue": TASK_INSTANCES_QUEUE,
    "No New Instance": TASK_INSTANCES_IGNORE_NEW,
    "Stop Existing": TASK_INSTANCES_STOP_EXISTING,
}
 
results = {
    0x0: "The operation completed successfully",
    0x1: "Incorrect or unknown function called",
    0x2: "File not found",
    0xA: "The environment is incorrect",
    0x41300: "Task is ready to run at its next scheduled time",
    0x41301: "Task is currently running",
    0x41302: "Task is disabled",
    0x41303: "Task has not yet run",
    0x41304: "There are no more runs scheduled for this task",
    0x41306: "Task was terminated by the user",
    0x8004130F: "Credentials became corrupted",
    0x8004131F: "An instance of this task is already running",
    0x800710E0: "The operator or administrator has refused the request",
    0x800704DD: "The service is not available (Run only when logged in?)",
    0xC000013A: "The application terminated as a result of CTRL+C",
    0xC06D007E: "Unknown software exception",
}
 
 
def __virtual__():
    """
    Only works on Windows systems
    """
    if salt.utils.platform.is_windows():
        if not HAS_DEPENDENCIES:
            log.warning("Could not load dependencies for %s", __virtualname__)
        return __virtualname__
    return False, "Module win_task: module only works on Windows systems"
 
 
def _get_date_time_format(dt_string):
    """
    Copied from win_system.py (_get_date_time_format)
    Function that detects the date/time format for the string passed.
    :param str dt_string:
        A date/time string
    :return: The format of the passed dt_string
    :rtype: str
    """
    valid_formats = [
        "%I:%M:%S %p",
        "%I:%M %p",
        "%H:%M:%S",
        "%H:%M",
        "%Y-%m-%d",
        "%m-%d-%y",
        "%m-%d-%Y",
        "%m/%d/%y",
        "%m/%d/%Y",
        "%Y/%m/%d",
    ]
    for dt_format in valid_formats:
        try:
            datetime.strptime(dt_string, dt_format)
            return dt_format
        except ValueError:
            continue
    return False
 
 
def _get_date_value(date):
    """
    Function for dealing with PyTime values with invalid dates. ie: 12/30/1899
    which is the windows task scheduler value for Never
    :param obj date: A PyTime object
    :return: A string value representing the date or the word "Never" for
    invalid date strings
    :rtype: str
    """
    try:
        return "{}".format(date)
    except ValueError:
        return "Never"
 
 
def _reverse_lookup(dictionary, value):
    """
    Lookup the key in a dictionary by its value. Will return the first match.
    :param dict dictionary: The dictionary to search
    :param str value: The value to search for.
    :return: Returns the first key to match the value
    :rtype: str
    """
    value_index = -1
    for idx, dict_value in enumerate(dictionary.values()):
        if type(dict_value) == list:
            if value in dict_value:
                value_index = idx
                break
        elif value == dict_value:
            value_index = idx
            break
 
    return list(dictionary)[value_index]
 
 
def _lookup_first(dictionary, key):
    """
    Lookup the first value given a key. Returns the first value if the key
    refers to a list or the value itself.
    :param dict dictionary: The dictionary to search
    :param str key: The key to get
    :return: Returns the first value available for the key
    :rtype: str
    """
    value = dictionary[key]
    if type(value) == list:
        return value[0]
    else:
        return value
 
 
def _save_task_definition(
    name, task_folder, task_definition, user_name, password, logon_type
):
    """
    Internal function to save the task definition.
    :param str name: The name of the task.
    :param str task_folder: The object representing the folder in which to save
    the task
    :param str task_definition: The object representing the task to be saved
    :param str user_name: The user_account under which to run the task
    :param str password: The password that corresponds to the user account
    :param int logon_type: The logon type for the task.
    :return: True if successful, False if not
    :rtype: bool
    """
    try:
        task_folder.RegisterTaskDefinition(
            name,
            task_definition,
            TASK_CREATE_OR_UPDATE,
            user_name,
            password,
            logon_type,
        )
 
        return True
 
    except pythoncom.com_error as error:
        hr, msg, exc, arg = error.args  # pylint: disable=W0633
        fc = {
            -2147024773: (
                "The filename, directory name, or volume label syntax is incorrect"
            ),
            -2147024894: "The system cannot find the file specified",
            -2147216615: "Required element or attribute missing",
            -2147216616: "Value incorrectly formatted or out of range",
            -2147352571: "Access denied",
        }
        try:
            failure_code = fc[exc[5]]
        except KeyError:
            failure_code = "Unknown Failure: {}".format(error)
 
        log.debug("Failed to modify task: %s", failure_code)
 
        return "Failed to modify task: {}".format(failure_code)
 
 
def list_tasks(location="\\"):
    r"""
    List all tasks located in a specific location in the task scheduler.
    Args:
        location (str):
            A string value representing the folder from which you want to list
            tasks. Default is ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        list: Returns a list of tasks
    CLI Example:
    .. code-block:: bash
        # List all tasks in the default location
        salt 'minion-id' task.list_tasks
        # List all tasks in the Microsoft\XblGameSave Directory
        salt 'minion-id' task.list_tasks Microsoft\XblGameSave
    """
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the folder to list tasks from
        task_folder = task_service.GetFolder(location)
        tasks = task_folder.GetTasks(0)
 
        ret = []
        for task in tasks:
            ret.append(task.Name)
 
    return ret
 
 
def list_folders(location="\\"):
    r"""
    List all folders located in a specific location in the task scheduler.
    Args:
        location (str):
            A string value representing the folder from which you want to list
            tasks. Default is ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        list: Returns a list of folders.
    CLI Example:
    .. code-block:: bash
        # List all folders in the default location
        salt 'minion-id' task.list_folders
        # List all folders in the Microsoft directory
        salt 'minion-id' task.list_folders Microsoft
    """
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the folder to list folders from
        task_folder = task_service.GetFolder(location)
        folders = task_folder.GetFolders(0)
 
        ret = []
        for folder in folders:
            ret.append(folder.Name)
 
    return ret
 
 
def list_triggers(name, location="\\"):
    r"""
    List all triggers that pertain to a task in the specified location.
    Args:
        name (str):
            The name of the task for which list triggers.
        location (str):
            A string value representing the location of the task from which to
            list triggers. Default is ``\`` which is the root for the task
            scheduler (``C:\Windows\System32\tasks``).
    Returns:
        list: Returns a list of triggers.
    CLI Example:
    .. code-block:: bash
        # List all triggers for a task in the default location
        salt 'minion-id' task.list_triggers <task_name>
        # List all triggers for the XblGameSaveTask in the Microsoft\XblGameSave
        # location
        salt '*' task.list_triggers XblGameSaveTask Microsoft\XblGameSave
    """
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the folder to list folders from
        task_folder = task_service.GetFolder(location)
        task_definition = task_folder.GetTask(name).Definition
        triggers = task_definition.Triggers
 
        ret = []
        for trigger in triggers:
            ret.append(trigger.Id)
 
    return ret
 
 
def list_actions(name, location="\\"):
    r"""
    List all actions that pertain to a task in the specified location.
    Args:
        name (str):
            The name of the task for which list actions.
        location (str):
            A string value representing the location of the task from which to
            list actions. Default is ``\`` which is the root for the task
            scheduler (``C:\Windows\System32\tasks``).
    Returns:
        list: Returns a list of actions.
    CLI Example:
    .. code-block:: bash
        # List all actions for a task in the default location
        salt 'minion-id' task.list_actions <task_name>
        # List all actions for the XblGameSaveTask in the Microsoft\XblGameSave
        # location
        salt 'minion-id' task.list_actions XblGameSaveTask Microsoft\XblGameSave
    """
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the folder to list folders from
        task_folder = task_service.GetFolder(location)
        task_definition = task_folder.GetTask(name).Definition
        actions = task_definition.Actions
 
        ret = []
        for action in actions:
            ret.append(action.Id)
 
    return ret
 
 
def create_task(
    name, location="\\", user_name="System", password=None, force=False, **kwargs
):
    r"""
    Create a new task in the designated location. This function has many keyword
    arguments that are not listed here. For additional arguments see:
        - :py:func:`edit_task`
        - :py:func:`add_action`
        - :py:func:`add_trigger`
    Args:
        name (str):
            The name of the task. This will be displayed in the task scheduler.
        location (str):
            A string value representing the location in which to create the
            task. Default is ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
        user_name (str):
            The user account under which to run the task. To specify the
            'System' account, use 'System'. The password will be ignored.
        password (str):
            The password to use for authentication. This should set the task to
            run whether the user is logged in or not, but is currently not
            working.
        force (bool):
            If the task exists, overwrite the existing task.
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.create_task <task_name> user_name=System force=True action_type=Execute cmd='del /Q /S C:\\Temp' trigger_type=Once start_date=2016-12-1 start_time=01:00
    """
    # Check for existing task
    if name in list_tasks(location) and not force:
        # Connect to an existing task definition
        return "{} already exists".format(name)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Create a new task definition
        task_definition = task_service.NewTask(0)
 
        # Modify task settings
        edit_task(
            task_definition=task_definition,
            user_name=user_name,
            password=password,
            **kwargs
        )
 
        # Add Action
        add_action(task_definition=task_definition, **kwargs)
 
        # Add Trigger
        add_trigger(task_definition=task_definition, **kwargs)
 
        # get the folder to create the task in
        task_folder = task_service.GetFolder(location)
 
        # Save the task
        _save_task_definition(
            name=name,
            task_folder=task_folder,
            task_definition=task_definition,
            user_name=task_definition.Principal.UserID,
            password=password,
            logon_type=task_definition.Principal.LogonType,
        )
 
    # Verify task was created
    return name in list_tasks(location)
 
 
def create_task_from_xml(
    name, location="\\", xml_text=None, xml_path=None, user_name="System", password=None
):
    r"""
    Create a task based on XML. Source can be a file or a string of XML.
    Args:
        name (str):
            The name of the task. This will be displayed in the task scheduler.
        location (str):
            A string value representing the location in which to create the
            task. Default is ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
        xml_text (str):
            A string of xml representing the task to be created. This will be
            overridden by ``xml_path`` if passed.
        xml_path (str):
            The path to an XML file on the local system containing the xml that
            defines the task. This will override ``xml_text``
        user_name (str):
            The user account under which to run the task. To specify the
            'System' account, use 'System'. The password will be ignored.
        password (str):
            The password to use for authentication. This should set the task to
            run whether the user is logged in or not, but is currently not
            working.
    Returns:
        bool: ``True`` if successful, otherwise ``False``
        str: A string with the error message if there is an error
    Raises:
        ArgumentValueError: If arguments are invalid
        CommandExecutionError
    CLI Example:
    .. code-block:: bash
        salt '*' task.create_task_from_xml <task_name> xml_path=C:\task.xml
    """
    # Check for existing task
    if name in list_tasks(location):
        # Connect to an existing task definition
        return "{} already exists".format(name)
 
    if not xml_text and not xml_path:
        raise ArgumentValueError("Must specify either xml_text or xml_path")
 
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Load xml from file, overrides xml_text
        # Need to figure out how to load contents of xml
        if xml_path:
            xml_text = xml_path
 
        # Get the folder to list folders from
        task_folder = task_service.GetFolder(location)
 
        # Determine logon type
        if user_name:
            if user_name.lower() == "system":
                logon_type = TASK_LOGON_SERVICE_ACCOUNT
                user_name = "SYSTEM"
                password = None
            else:
                if password:
                    logon_type = TASK_LOGON_PASSWORD
                else:
                    logon_type = TASK_LOGON_INTERACTIVE_TOKEN
        else:
            password = None
            logon_type = TASK_LOGON_NONE
 
        # Save the task
        try:
            task_folder.RegisterTask(
                name, xml_text, TASK_CREATE, user_name, password, logon_type
            )
 
        except pythoncom.com_error as error:
            hr, msg, exc, arg = error.args  # pylint: disable=W0633
            error_code = hex(exc[5] + 2 ** 32)
            fc = {
                0x80041319: "Required element or attribute missing",
                0x80041318: "Value incorrectly formatted or out of range",
                0x80020005: "Access denied",
                0x80041309: "A task's trigger is not found",
                0x8004130A: (
                    "One or more of the properties required to run this "
                    "task have not been set"
                ),
                0x8004130C: (
                    "The Task Scheduler service is not installed on this computer"
                ),
                0x8004130D: "The task object could not be opened",
                0x8004130E: (
                    "The object is either an invalid task object or is not "
                    "a task object"
                ),
                0x8004130F: (
                    "No account information could be found in the Task "
                    "Scheduler security database for the task indicated"
                ),
                0x80041310: "Unable to establish existence of the account specified",
                0x80041311: (
                    "Corruption was detected in the Task Scheduler "
                    "security database; the database has been reset"
                ),
                0x80041313: "The task object version is either unsupported or invalid",
                0x80041314: (
                    "The task has been configured with an unsupported "
                    "combination of account settings and run time options"
                ),
                0x80041315: "The Task Scheduler Service is not running",
                0x80041316: "The task XML contains an unexpected node",
                0x80041317: (
                    "The task XML contains an element or attribute from an "
                    "unexpected namespace"
                ),
                0x8004131A: "The task XML is malformed",
                0x0004131C: (
                    "The task is registered, but may fail to start. Batch "
                    "logon privilege needs to be enabled for the task principal"
                ),
                0x8004131D: "The task XML contains too many nodes of the same type",
            }
            try:
                failure_code = fc[error_code]
            except KeyError:
                failure_code = "Unknown Failure: {}".format(error_code)
            finally:
                log.debug("Failed to create task: %s", failure_code)
            raise CommandExecutionError(failure_code)
 
    # Verify creation
    return name in list_tasks(location)
 
 
def create_folder(name, location="\\"):
    r"""
    Create a folder in which to create tasks.
    Args:
        name (str):
            The name of the folder. This will be displayed in the task
            scheduler.
        location (str):
            A string value representing the location in which to create the
            folder. Default is ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.create_folder <folder_name>
    """
    # Check for existing folder
    if name in list_folders(location):
        # Connect to an existing task definition
        return "{} already exists".format(name)
 
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the folder to list folders from
        task_folder = task_service.GetFolder(location)
        task_folder.CreateFolder(name)
 
    # Verify creation
    return name in list_folders(location)
 
 
def edit_task(
    name=None,
    location="\\",
    # General Tab
    user_name=None,
    password=None,
    description=None,
    enabled=None,
    hidden=None,
    # Conditions Tab
    run_if_idle=None,
    idle_duration=None,
    idle_wait_timeout=None,
    idle_stop_on_end=None,
    idle_restart=None,
    ac_only=None,
    stop_if_on_batteries=None,
    wake_to_run=None,
    run_if_network=None,
    network_id=None,
    network_name=None,
    # Settings Tab
    allow_demand_start=None,
    start_when_available=None,
    restart_every=None,
    restart_count=3,
    execution_time_limit=None,
    force_stop=None,
    delete_after=None,
    multiple_instances=None,
    **kwargs
):
    r"""
    Edit the parameters of a task. Triggers and Actions cannot be edited yet.
    Args:
        name (str):
            The name of the task. This will be displayed in the task scheduler.
        location (str):
            A string value representing the location in which to create the
            task. Default is ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
        user_name (str):
            The user account under which to run the task. To specify the
            'System' account, use 'System'. The password will be ignored.
        password (str):
            The password to use for authentication. This should set the task to
            run whether the user is logged in or not, but is currently not
            working.
            .. note::
                The combination of user_name and password determine how the
                task runs. For example, if a username is passed without at
                password the task will only run when the user is logged in. If a
                password is passed as well the task will run whether the user is
                logged on or not. If you pass 'System' as the username the task
                will run as the system account (the password parameter is
                ignored).
        description (str):
            A string representing the text that will be displayed in the
            description field in the task scheduler.
        enabled (bool):
            A boolean value representing whether or not the task is enabled.
        hidden (bool):
            A boolean value representing whether or not the task is hidden.
        run_if_idle (bool):
            Boolean value that indicates that the Task Scheduler will run the
            task only if the computer is in an idle state.
        idle_duration (str):
            A value that indicates the amount of time that the computer must be
            in an idle state before the task is run. Valid values are:
                - 1 minute
                - 5 minutes
                - 10 minutes
                - 15 minutes
                - 30 minutes
                - 1 hour
        idle_wait_timeout (str):
            A value that indicates the amount of time that the Task Scheduler
            will wait for an idle condition to occur. Valid values are:
                - Do not wait
                - 1 minute
                - 5 minutes
                - 10 minutes
                - 15 minutes
                - 30 minutes
                - 1 hour
                - 2 hours
        idle_stop_on_end (bool):
            Boolean value that indicates that the Task Scheduler will terminate
            the task if the idle condition ends before the task is completed.
        idle_restart (bool):
            Boolean value that indicates whether the task is restarted when the
            computer cycles into an idle condition more than once.
        ac_only (bool):
            Boolean value that indicates that the Task Scheduler will launch the
            task only while on AC power.
        stop_if_on_batteries (bool):
            Boolean value that indicates that the task will be stopped if the
            computer begins to run on battery power.
        wake_to_run (bool):
            Boolean value that indicates that the Task Scheduler will wake the
            computer when it is time to run the task.
        run_if_network (bool):
            Boolean value that indicates that the Task Scheduler will run the
            task only when a network is available.
        network_id (guid):
            GUID value that identifies a network profile.
        network_name (str):
            Sets the name of a network profile. The name is used for display
            purposes.
        allow_demand_start (bool):
            Boolean value that indicates that the task can be started by using
            either the Run command or the Context menu.
        start_when_available (bool):
            Boolean value that indicates that the Task Scheduler can start the
            task at any time after its scheduled time has passed.
        restart_every (str):
            A value that specifies the interval between task restart attempts.
            Valid values are:
                - False (to disable)
                - 1 minute
                - 5 minutes
                - 10 minutes
                - 15 minutes
                - 30 minutes
                - 1 hour
                - 2 hours
        restart_count (int):
            The number of times the Task Scheduler will attempt to restart the
            task. Valid values are integers 1 - 999.
        execution_time_limit (bool, str):
            The amount of time allowed to complete the task. Valid values are:
                - False (to disable)
                - 1 hour
                - 2 hours
                - 4 hours
                - 8 hours
                - 12 hours
                - 1 day
                - 3 days
        force_stop (bool):
            Boolean value that indicates that the task may be terminated by
            using TerminateProcess.
        delete_after (bool, str):
            The amount of time that the Task Scheduler will wait before deleting
            the task after it expires. Requires a trigger with an expiration
            date. Valid values are:
                - False (to disable)
                - Immediately
                - 30 days
                - 90 days
                - 180 days
                - 365 days
        multiple_instances (str):
            Sets the policy that defines how the Task Scheduler deals with
            multiple instances of the task. Valid values are:
                - Parallel
                - Queue
                - No New Instance
                - Stop Existing
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt '*' task.edit_task <task_name> description='This task is awesome'
    """
    # TODO: Add more detailed return for items changed
 
    with salt.utils.winapi.Com():
        # Check for passed task_definition
        # If not passed, open a task definition for an existing task
        save_definition = False
        if kwargs.get("task_definition", False):
            task_definition = kwargs.get("task_definition")
        else:
            save_definition = True
 
            # Make sure a name was passed
            if not name:
                return 'Required parameter "name" not passed'
 
            # Make sure task exists to modify
            if name in list_tasks(location):
 
                # Connect to the task scheduler
                task_service = win32com.client.Dispatch("Schedule.Service")
                task_service.Connect()
 
                # get the folder to create the task in
                task_folder = task_service.GetFolder(location)
 
                # Connect to an existing task definition
                task_definition = task_folder.GetTask(name).Definition
 
            else:
                # Not found and create_new not set, return not found
                return "{} not found".format(name)
 
        # General Information
        if save_definition:
            task_definition.RegistrationInfo.Author = "Salt Minion"
            task_definition.RegistrationInfo.Source = "Salt Minion Daemon"
 
        if description is not None:
            task_definition.RegistrationInfo.Description = description
 
        # General Information: Security Options
        if user_name:
            # Determine logon type
            if user_name.lower() == "system":
                logon_type = TASK_LOGON_SERVICE_ACCOUNT
                user_name = "SYSTEM"
                password = None
            else:
                task_definition.Principal.Id = user_name
                if password:
                    logon_type = TASK_LOGON_PASSWORD
                else:
                    logon_type = TASK_LOGON_INTERACTIVE_TOKEN
 
            task_definition.Principal.UserID = user_name
            task_definition.Principal.DisplayName = user_name
            task_definition.Principal.LogonType = logon_type
            task_definition.Principal.RunLevel = TASK_RUNLEVEL_HIGHEST
        else:
            user_name = None
            password = None
 
        # Settings
        # https://msdn.microsoft.com/en-us/library/windows/desktop/aa383480(v=vs.85).aspx
        if enabled is not None:
            task_definition.Settings.Enabled = enabled
        # Settings: General Tab
        if hidden is not None:
            task_definition.Settings.Hidden = hidden
 
        # Settings: Conditions Tab (Idle)
        # https://msdn.microsoft.com/en-us/library/windows/desktop/aa380669(v=vs.85).aspx
        if run_if_idle is not None:
            task_definition.Settings.RunOnlyIfIdle = run_if_idle
 
        if task_definition.Settings.RunOnlyIfIdle:
            if idle_stop_on_end is not None:
                task_definition.Settings.IdleSettings.StopOnIdleEnd = idle_stop_on_end
            if idle_restart is not None:
                task_definition.Settings.IdleSettings.RestartOnIdle = idle_restart
            if idle_duration is not None:
                if idle_duration in duration:
                    task_definition.Settings.IdleSettings.IdleDuration = _lookup_first(
                        duration, idle_duration
                    )
                else:
                    return 'Invalid value for "idle_duration"'
            if idle_wait_timeout is not None:
                if idle_wait_timeout in duration:
                    task_definition.Settings.IdleSettings.WaitTimeout = _lookup_first(
                        duration, idle_wait_timeout
                    )
                else:
                    return 'Invalid value for "idle_wait_timeout"'
 
        # Settings: Conditions Tab (Power)
        if ac_only is not None:
            task_definition.Settings.DisallowStartIfOnBatteries = ac_only
        if stop_if_on_batteries is not None:
            task_definition.Settings.StopIfGoingOnBatteries = stop_if_on_batteries
        if wake_to_run is not None:
            task_definition.Settings.WakeToRun = wake_to_run
 
        # Settings: Conditions Tab (Network)
        # https://msdn.microsoft.com/en-us/library/windows/desktop/aa382067(v=vs.85).aspx
        if run_if_network is not None:
            task_definition.Settings.RunOnlyIfNetworkAvailable = run_if_network
        if task_definition.Settings.RunOnlyIfNetworkAvailable:
            if network_id:
                task_definition.Settings.NetworkSettings.Id = network_id
            if network_name:
                task_definition.Settings.NetworkSettings.Name = network_name
 
        # Settings: Settings Tab
        if allow_demand_start is not None:
            task_definition.Settings.AllowDemandStart = allow_demand_start
        if start_when_available is not None:
            task_definition.Settings.StartWhenAvailable = start_when_available
        if restart_every is not None:
            if restart_every is False:
                task_definition.Settings.RestartInterval = ""
            else:
                if restart_every in duration:
                    task_definition.Settings.RestartInterval = _lookup_first(
                        duration, restart_every
                    )
                else:
                    return 'Invalid value for "restart_every"'
        if task_definition.Settings.RestartInterval:
            if restart_count is not None:
                if restart_count in range(1, 999):
                    task_definition.Settings.RestartCount = restart_count
                else:
                    return '"restart_count" must be a value between 1 and 999'
        if execution_time_limit is not None:
            if execution_time_limit is False:
                task_definition.Settings.ExecutionTimeLimit = "PT0S"
            else:
                if execution_time_limit in duration:
                    task_definition.Settings.ExecutionTimeLimit = _lookup_first(
                        duration, execution_time_limit
                    )
                else:
                    return 'Invalid value for "execution_time_limit"'
        if force_stop is not None:
            task_definition.Settings.AllowHardTerminate = force_stop
        if delete_after is not None:
            # TODO: Check triggers for end_boundary
            if delete_after is False:
                task_definition.Settings.DeleteExpiredTaskAfter = ""
            if delete_after in duration:
                task_definition.Settings.DeleteExpiredTaskAfter = _lookup_first(
                    duration, delete_after
                )
            else:
                return 'Invalid value for "delete_after"'
        if multiple_instances is not None:
            task_definition.Settings.MultipleInstances = instances[multiple_instances]
 
        # Save the task
        if save_definition:
            # Save the Changes
            return _save_task_definition(
                name=name,
                task_folder=task_folder,
                task_definition=task_definition,
                user_name=user_name,
                password=password,
                logon_type=task_definition.Principal.LogonType,
            )
 
 
def delete_task(name, location="\\"):
    r"""
    Delete a task from the task scheduler.
    Args:
        name (str):
            The name of the task to delete.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.delete_task <task_name>
    """
    # Check for existing task
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder to delete the task from
        task_folder = task_service.GetFolder(location)
 
        task_folder.DeleteTask(name, 0)
 
    # Verify deletion
    return name not in list_tasks(location)
 
 
def delete_folder(name, location="\\"):
    r"""
    Delete a folder from the task scheduler.
    Args:
        name (str):
            The name of the folder to delete.
        location (str):
            A string value representing the location of the folder.  Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.delete_folder <folder_name>
    """
    # Check for existing folder
    if name not in list_folders(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder to delete the folder from
        task_folder = task_service.GetFolder(location)
 
        # Delete the folder
        task_folder.DeleteFolder(name, 0)
 
    # Verify deletion
    return name not in list_folders(location)
 
 
def run(name, location="\\"):
    r"""
    Run a scheduled task manually.
    Args:
        name (str):
            The name of the task to run.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.run <task_name>
    """
    # Check for existing folder
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder to delete the folder from
        task_folder = task_service.GetFolder(location)
        task = task_folder.GetTask(name)
 
        try:
            task.Run("")
            return True
        except pythoncom.com_error:
            return False
 
 
def run_wait(name, location="\\"):
    r"""
    Run a scheduled task and return when the task finishes
    Args:
        name (str):
            The name of the task to run.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.run_wait <task_name>
    """
    # Check for existing folder
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder to delete the folder from
        task_folder = task_service.GetFolder(location)
        task = task_folder.GetTask(name)
 
        # Is the task already running
        if task.State == TASK_STATE_RUNNING:
            return "Task already running"
 
        try:
            task.Run("")
            time.sleep(1)
            running = True
        except pythoncom.com_error:
            return False
 
        while running:
            running = False
            try:
                running_tasks = task_service.GetRunningTasks(0)
                if running_tasks.Count:
                    for item in running_tasks:
                        if item.Name == name:
                            running = True
            except pythoncom.com_error:
                running = False
 
    return True
 
 
def stop(name, location="\\"):
    r"""
    Stop a scheduled task.
    Args:
        name (str):
            The name of the task to stop.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.list_stop <task_name>
    """
    # Check for existing folder
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder to delete the folder from
        task_folder = task_service.GetFolder(location)
        task = task_folder.GetTask(name)
 
        try:
            task.Stop(0)
            return True
        except pythoncom.com_error:
            return False
 
 
def status(name, location="\\"):
    r"""
    Determine the status of a task. Is it Running, Queued, Ready, etc.
    Args:
        name (str):
            The name of the task for which to return the status
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        str: The current status of the task. Will be one of the following:
            - Unknown
            - Disabled
            - Queued
            - Ready
            - Running
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.list_status <task_name>
    """
    # Check for existing folder
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder where the task is defined
        task_folder = task_service.GetFolder(location)
        task = task_folder.GetTask(name)
 
        return states[task.State]
 
 
def info(name, location="\\"):
    r"""
    Get the details about a task in the task scheduler.
    Args:
        name (str):
            The name of the task for which to return the status
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        dict: A dictionary containing the task configuration
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.info <task_name>
    """
    # Check for existing folder
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # connect to the task scheduler
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # get the folder to delete the folder from
        task_folder = task_service.GetFolder(location)
        task = task_folder.GetTask(name)
 
        properties = {
            "enabled": task.Enabled,
            "last_run": _get_date_value(task.LastRunTime),
            "last_run_result": results[task.LastTaskResult],
            "missed_runs": task.NumberOfMissedRuns,
            "next_run": _get_date_value(task.NextRunTime),
            "status": states[task.State],
        }
 
        def_set = task.Definition.Settings
 
        settings = {
            "allow_demand_start": def_set.AllowDemandStart,
            "force_stop": def_set.AllowHardTerminate,
        }
 
        if def_set.DeleteExpiredTaskAfter == "":
            settings["delete_after"] = False
        elif def_set.DeleteExpiredTaskAfter == "PT0S":
            settings["delete_after"] = "Immediately"
        else:
            settings["delete_after"] = _reverse_lookup(
                duration, def_set.DeleteExpiredTaskAfter
            )
 
        if def_set.ExecutionTimeLimit == "":
            settings["execution_time_limit"] = False
        else:
            settings["execution_time_limit"] = _reverse_lookup(
                duration, def_set.ExecutionTimeLimit
            )
 
        settings["multiple_instances"] = _reverse_lookup(
            instances, def_set.MultipleInstances
        )
 
        if def_set.RestartInterval == "":
            settings["restart_interval"] = False
        else:
            settings["restart_interval"] = _reverse_lookup(
                duration, def_set.RestartInterval
            )
 
        if settings["restart_interval"]:
            settings["restart_count"] = def_set.RestartCount
        settings["stop_if_on_batteries"] = def_set.StopIfGoingOnBatteries
        settings["wake_to_run"] = def_set.WakeToRun
 
        conditions = {
            "ac_only": def_set.DisallowStartIfOnBatteries,
            "run_if_idle": def_set.RunOnlyIfIdle,
            "run_if_network": def_set.RunOnlyIfNetworkAvailable,
            "start_when_available": def_set.StartWhenAvailable,
        }
 
        if conditions["run_if_idle"]:
            idle_set = def_set.IdleSettings
            conditions["idle_duration"] = idle_set.IdleDuration
            conditions["idle_restart"] = idle_set.RestartOnIdle
            conditions["idle_stop_on_end"] = idle_set.StopOnIdleEnd
            conditions["idle_wait_timeout"] = idle_set.WaitTimeout
 
        if conditions["run_if_network"]:
            net_set = def_set.NetworkSettings
            conditions["network_id"] = net_set.Id
            conditions["network_name"] = net_set.Name
 
        actions = []
        for actionObj in task.Definition.Actions:
            action = {"action_type": _reverse_lookup(action_types, actionObj.Type)}
            if actionObj.Path:
                action["cmd"] = actionObj.Path
            if actionObj.Arguments:
                action["arguments"] = actionObj.Arguments
            if actionObj.WorkingDirectory:
                action["working_dir"] = actionObj.WorkingDirectory
            actions.append(action)
 
        triggers = []
        for triggerObj in task.Definition.Triggers:
            trigger = {"trigger_type": _reverse_lookup(trigger_types, triggerObj.Type)}
            if triggerObj.ExecutionTimeLimit:
                trigger["execution_time_limit"] = _reverse_lookup(
                    duration, triggerObj.ExecutionTimeLimit
                )
            if triggerObj.StartBoundary:
                start_date, start_time = triggerObj.StartBoundary.split("T", 1)
                trigger["start_date"] = start_date
                trigger["start_time"] = start_time
            if triggerObj.EndBoundary:
                end_date, end_time = triggerObj.EndBoundary.split("T", 1)
                trigger["end_date"] = end_date
                trigger["end_time"] = end_time
            trigger["enabled"] = triggerObj.Enabled
            if hasattr(triggerObj, "RandomDelay"):
                if triggerObj.RandomDelay:
                    trigger["random_delay"] = _reverse_lookup(
                        duration, triggerObj.RandomDelay
                    )
                else:
                    trigger["random_delay"] = False
            if hasattr(triggerObj, "Delay"):
                if triggerObj.Delay:
                    trigger["delay"] = _reverse_lookup(duration, triggerObj.Delay)
                else:
                    trigger["delay"] = False
            triggers.append(trigger)
 
        properties["settings"] = settings
        properties["conditions"] = conditions
        properties["actions"] = actions
        properties["triggers"] = triggers
        ret = properties
 
    return ret
 
 
def add_action(name=None, location="\\", action_type="Execute", **kwargs):
    r"""
    Add an action to a task.
    Args:
        name (str):
            The name of the task to which to add the action.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
        action_type (str):
            The type of action to add. There are three action types. Each one
            requires its own set of Keyword Arguments (kwargs). Valid values
            are:
                - Execute
                - Email
                - Message
    Required arguments for each action_type:
    **Execute**
        Execute a command or an executable
            cmd (str):
                (required) The command or executable to run.
            arguments (str):
                (optional) Arguments to be passed to the command or executable.
                To launch a script the first command will need to be the
                interpreter for the script. For example, to run a vbscript you
                would pass ``cscript.exe`` in the ``cmd`` parameter and pass the
                script in the ``arguments`` parameter as follows:
                    - ``cmd='cscript.exe' arguments='c:\scripts\myscript.vbs'``
                Batch files do not need an interpreter and may be passed to the
                cmd parameter directly.
            start_in (str):
                (optional) The current working directory for the command.
    **Email**
        Send and email. Requires ``server``, ``from``, and ``to`` or ``cc``.
            from (str): The sender
            reply_to (str): Who to reply to
            to (str): The recipient
            cc (str): The CC recipient
            bcc (str): The BCC recipient
            subject (str): The subject of the email
            body (str): The Message Body of the email
            server (str): The server used to send the email
            attachments (list):
                A list of attachments. These will be the paths to the files to
                attach. ie: ``attachments="['C:\attachment1.txt',
                'C:\attachment2.txt']"``
    **Message**
        Display a dialog box. The task must be set to "Run only when user is
        logged on" in order for the dialog box to display. Both parameters are
        required.
            title (str):
                The dialog box title.
            message (str):
                The dialog box message body
    Returns:
        dict: A dictionary containing the task configuration
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.add_action <task_name> cmd='del /Q /S C:\\Temp'
    """
    with salt.utils.winapi.Com():
        save_definition = False
        if kwargs.get("task_definition", False):
            task_definition = kwargs.get("task_definition")
        else:
            save_definition = True
            # Make sure a name was passed
            if not name:
                return 'Required parameter "name" not passed'
 
            # Make sure task exists
            if name in list_tasks(location):
 
                # Connect to the task scheduler
                task_service = win32com.client.Dispatch("Schedule.Service")
                task_service.Connect()
 
                # get the folder to create the task in
                task_folder = task_service.GetFolder(location)
 
                # Connect to an existing task definition
                task_definition = task_folder.GetTask(name).Definition
 
            else:
                # Not found and create_new not set, return not found
                return "{} not found".format(name)
 
        # Action Settings
        task_action = task_definition.Actions.Create(action_types[action_type])
        if action_types[action_type] == TASK_ACTION_EXEC:
            task_action.Id = "Execute_ID1"
            if kwargs.get("cmd", False):
                task_action.Path = kwargs.get("cmd")
            else:
                return 'Required parameter "cmd" not found'
            task_action.Arguments = kwargs.get("arguments", "")
            task_action.WorkingDirectory = kwargs.get("start_in", "")
 
        elif action_types[action_type] == TASK_ACTION_SEND_EMAIL:
            task_action.Id = "Email_ID1"
 
            # Required Parameters
            if kwargs.get("server", False):
                task_action.Server = kwargs.get("server")
            else:
                return 'Required parameter "server" not found'
 
            if kwargs.get("from", False):
                task_action.From = kwargs.get("from")
            else:
                return 'Required parameter "from" not found'
 
            if kwargs.get("to", False) or kwargs.get("cc", False):
                if kwargs.get("to"):
                    task_action.To = kwargs.get("to")
                if kwargs.get("cc"):
                    task_action.Cc = kwargs.get("cc")
            else:
                return 'Required parameter "to" or "cc" not found'
 
            # Optional Parameters
            if kwargs.get("reply_to"):
                task_action.ReplyTo = kwargs.get("reply_to")
            if kwargs.get("bcc"):
                task_action.Bcc = kwargs.get("bcc")
            if kwargs.get("subject"):
                task_action.Subject = kwargs.get("subject")
            if kwargs.get("body"):
                task_action.Body = kwargs.get("body")
            if kwargs.get("attachments"):
                task_action.Attachments = kwargs.get("attachments")
 
        elif action_types[action_type] == TASK_ACTION_SHOW_MESSAGE:
            task_action.Id = "Message_ID1"
 
            if kwargs.get("title", False):
                task_action.Title = kwargs.get("title")
            else:
                return 'Required parameter "title" not found'
 
            if kwargs.get("message", False):
                task_action.MessageBody = kwargs.get("message")
            else:
                return 'Required parameter "message" not found'
 
        # Save the task
        if save_definition:
            # Save the Changes
            return _save_task_definition(
                name=name,
                task_folder=task_folder,
                task_definition=task_definition,
                user_name=task_definition.Principal.UserID,
                password=None,
                logon_type=task_definition.Principal.LogonType,
            )
 
 
def _clear_actions(name, location="\\"):
    r"""
    Remove all actions from the task.
    :param str name: The name of the task from which to clear all actions.
    :param str location: A string value representing the location of the task.
    Default is ``\`` which is the root for the task scheduler
    (``C:\Windows\System32\tasks``).
    :return: True if successful, False if unsuccessful
    :rtype: bool
    """
    # TODO: The problem is, you have to have at least one action for the task to
    # TODO: be valid, so this will always fail with a 'Required element or
    # TODO: attribute missing' error.
    # TODO: Make this an internal function that clears the functions but doesn't
    # TODO: save it. Then you can add a new function. Maybe for editing an
    # TODO: action.
    # Check for existing task
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the actions from the task
        task_folder = task_service.GetFolder(location)
        task_definition = task_folder.GetTask(name).Definition
        actions = task_definition.Actions
 
        actions.Clear()
 
        # Save the Changes
        return _save_task_definition(
            name=name,
            task_folder=task_folder,
            task_definition=task_definition,
            user_name=task_definition.Principal.UserID,
            password=None,
            logon_type=task_definition.Principal.LogonType,
        )
 
 
def add_trigger(
    name=None,
    location="\\",
    trigger_type=None,
    trigger_enabled=True,
    start_date=None,
    start_time=None,
    end_date=None,
    end_time=None,
    random_delay=None,
    repeat_interval=None,
    repeat_duration=None,
    repeat_stop_at_duration_end=False,
    execution_time_limit=None,
    delay=None,
    **kwargs
):
    r"""
    Add a trigger to a Windows Scheduled task
    .. note::
        Arguments are parsed by the YAML loader and are subject to
        yaml's idiosyncrasies. Therefore, time values in some
        formats (``%H:%M:%S`` and ``%H:%M``) should to be quoted.
        See `YAML IDIOSYNCRASIES`_ for more details.
    .. _`YAML IDIOSYNCRASIES`: https://docs.saltproject.io/en/latest/topics/troubleshooting/yaml_idiosyncrasies.html#time-expressions
    Args:
        name (str):
            The name of the task to which to add the trigger.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
        trigger_type (str):
            The type of trigger to create. This is defined when the trigger is
            created and cannot be changed later. Options are as follows:
                - Event
                - Once
                - Daily
                - Weekly
                - Monthly
                - MonthlyDay
                - OnIdle
                - OnTaskCreation
                - OnBoot
                - OnLogon
                - OnSessionChange
        trigger_enabled (bool):
            Boolean value that indicates whether the trigger is enabled.
        start_date (str):
            The date when the trigger is activated. If no value is passed, the
            current date will be used. Can be one of the following formats:
                - %Y-%m-%d
                - %m-%d-%y
                - %m-%d-%Y
                - %m/%d/%y
                - %m/%d/%Y
                - %Y/%m/%d
        start_time (str):
            The time when the trigger is activated. If no value is passed,
            midnight will be used. Can be one of the following formats:
                - %I:%M:%S %p
                - %I:%M %p
                - %H:%M:%S
                - %H:%M
        end_date (str):
            The date when the trigger is deactivated. The trigger cannot start
            the task after it is deactivated. Can be one of the following
            formats:
                - %Y-%m-%d
                - %m-%d-%y
                - %m-%d-%Y
                - %m/%d/%y
                - %m/%d/%Y
                - %Y/%m/%d
        end_time (str):
            The time when the trigger is deactivated. If this is not passed
            with ``end_date`` it will be set to midnight. Can be one of the
            following formats:
                - %I:%M:%S %p
                - %I:%M %p
                - %H:%M:%S
                - %H:%M
        random_delay (str):
            The delay time that is randomly added to the start time of the
            trigger. Valid values are:
                - 30 seconds
                - 1 minute
                - 30 minutes
                - 1 hour
                - 8 hours
                - 1 day
            .. note::
                This parameter applies to the following trigger types
                    - Once
                    - Daily
                    - Weekly
                    - Monthly
                    - MonthlyDay
        repeat_interval (str):
            The amount of time between each restart of the task. Valid values
            are:
                - 5 minutes
                - 10 minutes
                - 15 minutes
                - 30 minutes
                - 1 hour
        repeat_duration (str):
            How long the pattern is repeated. Valid values are:
                - Indefinitely
                - 15 minutes
                - 30 minutes
                - 1 hour
                - 12 hours
                - 1 day
        repeat_stop_at_duration_end (bool):
            Boolean value that indicates if a running instance of the task is
            stopped at the end of the repetition pattern duration.
        execution_time_limit (str):
            The maximum amount of time that the task launched by the trigger is
            allowed to run. Valid values are:
                - 30 minutes
                - 1 hour
                - 2 hours
                - 4 hours
                - 8 hours
                - 12 hours
                - 1 day
                - 3 days (default)
        delay (str):
            The time the trigger waits after its activation to start the task.
            Valid values are:
                - 15 seconds
                - 30 seconds
                - 1 minute
                - 30 minutes
                - 1 hour
                - 8 hours
                - 1 day
            .. note::
                This parameter applies to the following trigger types:
                    - OnLogon
                    - OnBoot
                    - Event
                    - OnTaskCreation
                    - OnSessionChange
    **kwargs**
    There are optional keyword arguments determined by the type of trigger
    being defined. They are as follows:
    *Event*
        The trigger will be fired by an event.
            subscription (str):
                An event definition in xml format that fires the trigger. The
                easiest way to get this would is to create an event in Windows
                Task Scheduler and then copy the xml text.
    *Once*
        No special parameters required.
    *Daily*
        The task will run daily.
            days_interval (int):
                The interval between days in the schedule. An interval of 1
                produces a daily schedule. An interval of 2 produces an
                every-other day schedule. If no interval is specified, 1 is
                used. Valid entries are 1 - 999.
    *Weekly*
        The task will run weekly.
            weeks_interval (int):
                The interval between weeks in the schedule. An interval of 1
                produces a weekly schedule. An interval of 2 produces an
                every-other week schedule. If no interval is specified, 1 is
                used. Valid entries are 1 - 52.
            days_of_week (list):
                Sets the days of the week on which the task runs. Should be a
                list. ie: ``['Monday','Wednesday','Friday']``. Valid entries are
                the names of the days of the week.
    *Monthly*
        The task will run monthly.
            months_of_year (list):
                Sets the months of the year during which the task runs. Should
                be a list. ie: ``['January','July']``. Valid entries are the
                full names of all the months.
            days_of_month (list):
                Sets the days of the month during which the task runs. Should be
                a list. ie: ``[1, 15, 'Last']``. Options are all days of the
                month 1 - 31 and the word 'Last' to indicate the last day of the
                month.
            last_day_of_month (bool):
                Boolean value that indicates that the task runs on the last day
                of the month regardless of the actual date of that day.
                .. note::
                    You can set the task to run on the last day of the month by
                    either including the word 'Last' in the list of days, or
                    setting the parameter 'last_day_of_month' equal to ``True``.
    *MonthlyDay*
        The task will run monthly on the specified day.
            months_of_year (list):
                Sets the months of the year during which the task runs. Should
                be a list. ie: ``['January','July']``. Valid entries are the
                full names of all the months.
            weeks_of_month (list):
                Sets the weeks of the month during which the task runs. Should
                be a list. ie: ``['First','Third']``. Valid options are:
                    - First
                    - Second
                    - Third
                    - Fourth
            last_week_of_month (bool):
                Boolean value that indicates that the task runs on the last week
                of the month.
            days_of_week (list):
                Sets the days of the week during which the task runs. Should be
                a list. ie: ``['Monday','Wednesday','Friday']``.  Valid entries
                are the names of the days of the week.
    *OnIdle*
        No special parameters required.
    *OnTaskCreation*
        No special parameters required.
    *OnBoot*
        No special parameters required.
    *OnLogon*
        No special parameters required.
    *OnSessionChange*
        The task will be triggered by a session change.
            session_user_name (str):
                Sets the user for the Terminal Server session. When a session
                state change is detected for this user, a task is started. To
                detect session status change for any user, do not pass this
                parameter.
            state_change (str):
                Sets the kind of Terminal Server session change that would
                trigger a task launch. Valid options are:
                    - ConsoleConnect: When you connect to a user session (switch
                      users)
                    - ConsoleDisconnect: When you disconnect a user session
                      (switch users)
                    - RemoteConnect: When a user connects via Remote Desktop
                    - RemoteDisconnect: When a user disconnects via Remote
                      Desktop
                    - SessionLock: When the workstation is locked
                    - SessionUnlock: When the workstation is unlocked
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.add_trigger <task_name> trigger_type=Once trigger_enabled=True start_date=2016/12/1 start_time='"12:01"'
    """
    if not trigger_type:
        return 'Required parameter "trigger_type" not specified'
 
    # Define lookup dictionaries
    state_changes = {
        "ConsoleConnect": 1,
        "ConsoleDisconnect": 2,
        "RemoteConnect": 3,
        "RemoteDisconnect": 4,
        "SessionLock": 7,
        "SessionUnlock": 8,
    }
 
    days = {
        1: 0x1,
        2: 0x2,
        3: 0x4,
        4: 0x8,
        5: 0x10,
        6: 0x20,
        7: 0x40,
        8: 0x80,
        9: 0x100,
        10: 0x200,
        11: 0x400,
        12: 0x800,
        13: 0x1000,
        14: 0x2000,
        15: 0x4000,
        16: 0x8000,
        17: 0x10000,
        18: 0x20000,
        19: 0x40000,
        20: 0x80000,
        21: 0x100000,
        22: 0x200000,
        23: 0x400000,
        24: 0x800000,
        25: 0x1000000,
        26: 0x2000000,
        27: 0x4000000,
        28: 0x8000000,
        29: 0x10000000,
        30: 0x20000000,
        31: 0x40000000,
        "Last": 0x80000000,
    }
 
    weekdays = {
        "Sunday": 0x1,
        "Monday": 0x2,
        "Tuesday": 0x4,
        "Wednesday": 0x8,
        "Thursday": 0x10,
        "Friday": 0x20,
        "Saturday": 0x40,
    }
 
    weeks = {"First": 0x1, "Second": 0x2, "Third": 0x4, "Fourth": 0x8}
 
    months = {
        "January": 0x1,
        "February": 0x2,
        "March": 0x4,
        "April": 0x8,
        "May": 0x10,
        "June": 0x20,
        "July": 0x40,
        "August": 0x80,
        "September": 0x100,
        "October": 0x200,
        "November": 0x400,
        "December": 0x800,
    }
 
    # Format Date Parameters
    if start_date:
        date_format = _get_date_time_format(start_date)
        if date_format:
            dt_obj = datetime.strptime(start_date, date_format)
        else:
            return "Invalid start_date"
    else:
        dt_obj = datetime.now()
 
    if start_time:
        time_format = _get_date_time_format(start_time)
        if time_format:
            tm_obj = datetime.strptime(start_time, time_format)
        else:
            return "Invalid start_time"
    else:
        tm_obj = datetime.strptime("00:00:00", "%H:%M:%S")
 
    start_boundary = "{}T{}".format(
        dt_obj.strftime("%Y-%m-%d"), tm_obj.strftime("%H:%M:%S")
    )
 
    dt_obj = None
    if end_date:
        date_format = _get_date_time_format(end_date)
        if date_format:
            dt_obj = datetime.strptime(end_date, date_format)
        else:
            return "Invalid end_date"
 
    if end_time:
        time_format = _get_date_time_format(end_time)
        if time_format:
            tm_obj = datetime.strptime(end_time, time_format)
        else:
            return "Invalid end_time"
    else:
        tm_obj = datetime.strptime("00:00:00", "%H:%M:%S")
 
    end_boundary = None
    if dt_obj and tm_obj:
        end_boundary = "{}T{}".format(
            dt_obj.strftime("%Y-%m-%d"), tm_obj.strftime("%H:%M:%S")
        )
 
    with salt.utils.winapi.Com():
        save_definition = False
        if kwargs.get("task_definition", False):
            task_definition = kwargs.get("task_definition")
        else:
            save_definition = True
            # Make sure a name was passed
            if not name:
                return 'Required parameter "name" not passed'
 
            # Make sure task exists
            if name in list_tasks(location):
 
                # Connect to the task scheduler
                task_service = win32com.client.Dispatch("Schedule.Service")
                task_service.Connect()
 
                # get the folder to create the task in
                task_folder = task_service.GetFolder(location)
 
                # Connect to an existing task definition
                task_definition = task_folder.GetTask(name).Definition
 
            else:
                # Not found and create_new not set, return not found
                return "{} not found".format(name)
 
        # Create a New Trigger
        trigger = task_definition.Triggers.Create(trigger_types[trigger_type])
 
        # Shared Trigger Parameters
        # Settings
        trigger.StartBoundary = start_boundary
        # Advanced Settings
        if delay:
            trigger.Delay = _lookup_first(duration, delay)
        if random_delay:
            trigger.RandomDelay = _lookup_first(duration, random_delay)
        if repeat_interval:
            trigger.Repetition.Interval = _lookup_first(duration, repeat_interval)
            if repeat_duration:
                trigger.Repetition.Duration = _lookup_first(duration, repeat_duration)
            trigger.Repetition.StopAtDurationEnd = repeat_stop_at_duration_end
        if execution_time_limit:
            trigger.ExecutionTimeLimit = _lookup_first(duration, execution_time_limit)
        if end_boundary:
            trigger.EndBoundary = end_boundary
        trigger.Enabled = trigger_enabled
 
        # Trigger Specific Parameters
        # Event Trigger Parameters
        if trigger_types[trigger_type] == TASK_TRIGGER_EVENT:
            # Check for required kwargs
            if kwargs.get("subscription", False):
                trigger.Id = "Event_ID1"
                trigger.Subscription = kwargs.get("subscription")
            else:
                return 'Required parameter "subscription" not passed'
 
        elif trigger_types[trigger_type] == TASK_TRIGGER_TIME:
            trigger.Id = "Once_ID1"
 
        # Daily Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_DAILY:
            trigger.Id = "Daily_ID1"
            trigger.DaysInterval = kwargs.get("days_interval", 1)
 
        # Weekly Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_WEEKLY:
            trigger.Id = "Weekly_ID1"
            trigger.WeeksInterval = kwargs.get("weeks_interval", 1)
            if kwargs.get("days_of_week", False):
                bits_days = 0
                for weekday in kwargs.get("days_of_week"):
                    bits_days |= weekdays[weekday]
                trigger.DaysOfWeek = bits_days
            else:
                return 'Required parameter "days_of_week" not passed'
 
        # Monthly Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLY:
            trigger.Id = "Monthly_ID1"
            if kwargs.get("months_of_year", False):
                bits_months = 0
                for month in kwargs.get("months_of_year"):
                    bits_months |= months[month]
                trigger.MonthsOfYear = bits_months
            else:
                return 'Required parameter "months_of_year" not passed'
 
            if kwargs.get("days_of_month", False) or kwargs.get(
                "last_day_of_month", False
            ):
                if kwargs.get("days_of_month", False):
                    bits_days = 0
                    for day in kwargs.get("days_of_month"):
                        bits_days |= days[day]
                    trigger.DaysOfMonth = bits_days
                trigger.RunOnLastDayOfMonth = kwargs.get("last_day_of_month", False)
            else:
                return (
                    'Monthly trigger requires "days_of_month" or "last_day_of_'
                    'month" parameters'
                )
 
        # Monthly Day Of Week Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_MONTHLYDOW:
            trigger.Id = "Monthly_DOW_ID1"
            if kwargs.get("months_of_year", False):
                bits_months = 0
                for month in kwargs.get("months_of_year"):
                    bits_months |= months[month]
                trigger.MonthsOfYear = bits_months
            else:
                return 'Required parameter "months_of_year" not passed'
 
            if kwargs.get("weeks_of_month", False) or kwargs.get(
                "last_week_of_month", False
            ):
                if kwargs.get("weeks_of_month", False):
                    bits_weeks = 0
                    for week in kwargs.get("weeks_of_month"):
                        bits_weeks |= weeks[week]
                    trigger.WeeksOfMonth = bits_weeks
                trigger.RunOnLastWeekOfMonth = kwargs.get("last_week_of_month", False)
            else:
                return (
                    'Monthly DOW trigger requires "weeks_of_month" or "last_'
                    'week_of_month" parameters'
                )
 
            if kwargs.get("days_of_week", False):
                bits_days = 0
                for weekday in kwargs.get("days_of_week"):
                    bits_days |= weekdays[weekday]
                trigger.DaysOfWeek = bits_days
            else:
                return 'Required parameter "days_of_week" not passed'
 
        # On Idle Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_IDLE:
            trigger.Id = "OnIdle_ID1"
 
        # On Task Creation Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_REGISTRATION:
            trigger.Id = "OnTaskCreation_ID1"
 
        # On Boot Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_BOOT:
            trigger.Id = "OnBoot_ID1"
 
        # On Logon Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_LOGON:
            trigger.Id = "OnLogon_ID1"
 
        # On Session State Change Trigger Parameters
        elif trigger_types[trigger_type] == TASK_TRIGGER_SESSION_STATE_CHANGE:
            trigger.Id = "OnSessionStateChange_ID1"
            if kwargs.get("session_user_name", False):
                trigger.UserId = kwargs.get("session_user_name")
            if kwargs.get("state_change", False):
                trigger.StateChange = state_changes[kwargs.get("state_change")]
            else:
                return 'Required parameter "state_change" not passed'
 
        # Save the task
        if save_definition:
            # Save the Changes
            return _save_task_definition(
                name=name,
                task_folder=task_folder,
                task_definition=task_definition,
                user_name=task_definition.Principal.UserID,
                password=None,
                logon_type=task_definition.Principal.LogonType,
            )
 
 
def clear_triggers(name, location="\\"):
    r"""
    Remove all triggers from the task.
    Args:
        name (str):
            The name of the task from which to clear all triggers.
        location (str):
            A string value representing the location of the task. Default is
            ``\`` which is the root for the task scheduler
            (``C:\Windows\System32\tasks``).
    Returns:
        bool: ``True`` if successful, otherwise ``False``
    CLI Example:
    .. code-block:: bash
        salt 'minion-id' task.clear_trigger <task_name>
    """
    # Check for existing task
    if name not in list_tasks(location):
        return "{} not found in {}".format(name, location)
 
    # Create the task service object
    with salt.utils.winapi.Com():
        task_service = win32com.client.Dispatch("Schedule.Service")
        task_service.Connect()
 
        # Get the triggers from the task
        task_folder = task_service.GetFolder(location)
        task_definition = task_folder.GetTask(name).Definition
        triggers = task_definition.Triggers
 
        triggers.Clear()
 
        # Save the Changes
        return _save_task_definition(
            name=name,
            task_folder=task_folder,
            task_definition=task_definition,
            user_name=task_definition.Principal.UserID,
            password=None,
            logon_type=task_definition.Principal.LogonType,
        )

  

posted @   CrossPython  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示