-
Notifications
You must be signed in to change notification settings - Fork 82
/
DSC_ScheduledTask.psm1
1893 lines (1516 loc) · 61.2 KB
/
DSC_ScheduledTask.psm1
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
Add-Type -TypeDefinition @'
namespace ScheduledTask
{
public enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
}
'@
$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules'
# Import the ComputerManagementDsc Common Modules
Import-Module -Name (Join-Path -Path $modulePath `
-ChildPath (Join-Path -Path 'ComputerManagementDsc.Common' `
-ChildPath 'ComputerManagementDsc.Common.psm1'))
# Import Localization Strings
$script:localizedData = Get-LocalizedData -ResourceName 'DSC_ScheduledTask'
<#
.SYNOPSIS
Gets the current state of the resource.
.PARAMETER TaskName
The name of the task.
.PARAMETER TaskPath
The path to the task - defaults to the root directory.
#>
function Get-TargetResource
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$TaskName,
[Parameter()]
[System.String]
$TaskPath = '\'
)
$TaskPath = ConvertTo-NormalizedTaskPath -TaskPath $TaskPath
Write-Verbose -Message ($script:localizedData.GetScheduledTaskMessage -f $TaskName, $TaskPath)
return Get-CurrentResource @PSBoundParameters
}
<#
.SYNOPSIS
Tests if the current resource state matches the desired resource state.
.PARAMETER TaskName
The name of the task.
.PARAMETER TaskPath
The path to the task - defaults to the root directory.
.PARAMETER Description
The task description.
.PARAMETER ActionExecutable
The path to the .exe for this task.
.PARAMETER ActionArguments
The arguments to pass the executable.
.PARAMETER ActionWorkingPath
The working path to specify for the executable.
.PARAMETER ScheduleType
When should the task be executed.
.PARAMETER RepeatInterval
How many units (minutes, hours, days) between each run of this task?
.PARAMETER StartTime
The time of day this task should start at - defaults to 12:00 AM. Not valid for
AtLogon and AtStartup tasks.
.PARAMETER SynchronizeAcrossTimeZone
Enable the scheduled task option to synchronize across time zones. This is enabled
by including the timezone offset in the scheduled task trigger. Defaults to false
which does not include the timezone offset.
.PARAMETER Ensure
Present if the task should exist, Absent if it should be removed.
.PARAMETER Enable
True if the task should be enabled, false if it should be disabled.
.PARAMETER BuiltInAccount
Run the task as one of the built in service accounts.
When set ExecuteAsCredential will be ignored and LogonType will be set to 'ServiceAccount'
.PARAMETER ExecuteAsCredential
The credential this task should execute as. If not specified defaults to running
as the local system account. Cannot be used in combination with ExecuteAsGMSA.
.PARAMETER ExecuteAsGMSA
The gMSA (Group Managed Service Account) this task should execute as. Cannot be
used in combination with ExecuteAsCredential.
.PARAMETER DaysInterval
Specifies the interval between the days in the schedule. An interval of 1 produces
a daily schedule. An interval of 2 produces an every-other day schedule.
.PARAMETER RandomDelay
Specifies a random amount of time to delay the start time of the trigger. The
delay time is a random time between the time the task triggers and the time that
you specify in this setting.
.PARAMETER RepetitionDuration
Specifies how long the repetition pattern repeats after the task starts.
.PARAMETER DaysOfWeek
Specifies an array of the days of the week on which Task Scheduler runs the task.
.PARAMETER WeeksInterval
Specifies the interval between the weeks in the schedule. An interval of 1 produces
a weekly schedule. An interval of 2 produces an every-other week schedule.
.PARAMETER User
Specifies the identifier of the user for a trigger that starts a task when a
user logs on.
.PARAMETER DisallowDemandStart
Indicates whether the task is prohibited to run on demand or not. Defaults
to $false.
.PARAMETER DisallowHardTerminate
Indicates whether the task is prohibited to be terminated or not. Defaults
to $false.
.PARAMETER Compatibility
The task compatibility level. Defaults to Vista.
.PARAMETER AllowStartIfOnBatteries
Indicates whether the task should start if the machine is on batteries or not.
Defaults to $false.
.PARAMETER Hidden
Indicates that the task is hidden in the Task Scheduler UI.
.PARAMETER RunOnlyIfIdle
Indicates that Task Scheduler runs the task only when the computer is idle.
.PARAMETER IdleWaitTimeout
Specifies the amount of time that Task Scheduler waits for an idle condition to occur.
.PARAMETER NetworkName
Specifies the name of a network profile that Task Scheduler uses to determine
if the task can run.
The Task Scheduler UI uses this setting for display purposes. Specify a network
name if you specify the RunOnlyIfNetworkAvailable parameter.
.PARAMETER DisallowStartOnRemoteAppSession
Indicates that the task does not start if the task is triggered to run in a Remote
Applications Integrated Locally (RAIL) session.
.PARAMETER StartWhenAvailable
Indicates that Task Scheduler can start the task at any time after its scheduled
time has passed.
.PARAMETER DontStopIfGoingOnBatteries
Indicates that the task does not stop if the computer switches to battery power.
.PARAMETER WakeToRun
Indicates that Task Scheduler wakes the computer before it runs the task.
.PARAMETER IdleDuration
Specifies the amount of time that the computer must be in an idle state before
Task Scheduler runs the task.
.PARAMETER RestartOnIdle
Indicates that Task Scheduler restarts the task when the computer cycles into an
idle condition more than once.
.PARAMETER DontStopOnIdleEnd
Indicates that Task Scheduler does not terminate the task if the idle condition
ends before the task is completed.
.PARAMETER ExecutionTimeLimit
Specifies the amount of time that Task Scheduler is allowed to complete the task.
.PARAMETER MultipleInstances
Specifies the policy that defines how Task Scheduler handles multiple instances
of the task.
.PARAMETER Priority
Specifies the priority level of the task. Priority must be an integer from 0 (highest priority)
to 10 (lowest priority). The default value is 7. Priority levels 7 and 8 are
used for background tasks. Priority levels 4, 5, and 6 are used for interactive tasks.
.PARAMETER RestartCount
Specifies the number of times that Task Scheduler attempts to restart the task.
.PARAMETER RestartInterval
Specifies the amount of time that Task Scheduler attempts to restart the task.
.PARAMETER RunOnlyIfNetworkAvailable
Indicates that Task Scheduler runs the task only when a network is available. Task
Scheduler uses the NetworkID parameter and NetworkName parameter that you specify
in this cmdlet to determine if the network is available.\
.PARAMETER RunLevel
Specifies the level of user rights that Task Scheduler uses to run the tasks that
are associated with the principal. Defaults to 'Limited'.
.PARAMETER LogonType
Specifies the security logon method that Task Scheduler uses to run the tasks that
are associated with the principal.
.PARAMETER EventSubscription
The event subscription in a string that can be parsed as valid XML. This parameter is only
valid in combination with the OnEvent Schedule Type. For the query schema please check:
https://docs.microsoft.com/en-us/windows/desktop/WES/queryschema-schema
.PARAMETER Delay
The time to wait after an event based trigger was triggered. This parameter is only
valid in combination with the OnEvent Schedule Type.
#>
function Set-TargetResource
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$TaskName,
[Parameter()]
[System.String]
$TaskPath = '\',
[Parameter()]
[System.String]
$Description,
[Parameter()]
[System.String]
$ActionExecutable,
[Parameter()]
[System.String]
$ActionArguments,
[Parameter()]
[System.String]
$ActionWorkingPath,
[Parameter()]
[System.String]
[ValidateSet('Once', 'Daily', 'Weekly', 'AtStartup', 'AtLogOn', 'OnEvent')]
$ScheduleType,
[Parameter()]
[System.String]
$RepeatInterval = '00:00:00',
[Parameter()]
[System.DateTime]
$StartTime = [System.DateTime]::Today,
[Parameter()]
[System.Boolean]
$SynchronizeAcrossTimeZone = $false,
[Parameter()]
[System.String]
[ValidateSet('Present', 'Absent')]
$Ensure = 'Present',
[Parameter()]
[System.Boolean]
$Enable = $true,
[Parameter()]
[ValidateSet('SYSTEM', 'LOCAL SERVICE', 'NETWORK SERVICE')]
[System.String]
$BuiltInAccount,
[Parameter()]
[System.Management.Automation.PSCredential]
$ExecuteAsCredential,
[Parameter()]
[System.String]
$ExecuteAsGMSA,
[Parameter()]
[System.UInt32]
$DaysInterval = 1,
[Parameter()]
[System.String]
$RandomDelay = '00:00:00',
[Parameter()]
[System.String]
$RepetitionDuration = '00:00:00',
[Parameter()]
[System.String[]]
$DaysOfWeek,
[Parameter()]
[System.UInt32]
$WeeksInterval = 1,
[Parameter()]
[System.String]
$User,
[Parameter()]
[System.Boolean]
$DisallowDemandStart = $false,
[Parameter()]
[System.Boolean]
$DisallowHardTerminate = $false,
[Parameter()]
[ValidateSet('AT', 'V1', 'Vista', 'Win7', 'Win8')]
[System.String]
$Compatibility = 'Vista',
[Parameter()]
[System.Boolean]
$AllowStartIfOnBatteries = $false,
[Parameter()]
[System.Boolean]
$Hidden = $false,
[Parameter()]
[System.Boolean]
$RunOnlyIfIdle = $false,
[Parameter()]
[System.String]
$IdleWaitTimeout = '02:00:00',
[Parameter()]
[System.String]
$NetworkName,
[Parameter()]
[System.Boolean]
$DisallowStartOnRemoteAppSession = $false,
[Parameter()]
[System.Boolean]
$StartWhenAvailable = $false,
[Parameter()]
[System.Boolean]
$DontStopIfGoingOnBatteries = $false,
[Parameter()]
[System.Boolean]
$WakeToRun = $false,
[Parameter()]
[System.String]
$IdleDuration = '01:00:00',
[Parameter()]
[System.Boolean]
$RestartOnIdle = $false,
[Parameter()]
[System.Boolean]
$DontStopOnIdleEnd = $false,
[Parameter()]
[System.String]
$ExecutionTimeLimit = '08:00:00',
[Parameter()]
[ValidateSet('IgnoreNew', 'Parallel', 'Queue')]
[System.String]
$MultipleInstances = 'Queue',
[Parameter()]
[System.UInt32]
$Priority = 7,
[Parameter()]
[System.UInt32]
$RestartCount = 0,
[Parameter()]
[System.String]
$RestartInterval = '00:00:00',
[Parameter()]
[System.Boolean]
$RunOnlyIfNetworkAvailable = $false,
[Parameter()]
[ValidateSet('Limited', 'Highest')]
[System.String]
$RunLevel = 'Limited',
[Parameter()]
[ValidateSet('Group', 'Interactive', 'InteractiveOrPassword', 'None', 'Password', 'S4U', 'ServiceAccount')]
[System.String]
$LogonType,
[Parameter()]
[System.String]
$EventSubscription,
[Parameter()]
[System.String]
$Delay = '00:00:00'
)
$TaskPath = ConvertTo-NormalizedTaskPath -TaskPath $TaskPath
Write-Verbose -Message ($script:localizedData.SetScheduledTaskMessage -f $TaskName, $TaskPath)
# Convert the strings containing time spans to TimeSpan Objects
[System.TimeSpan] $RepeatInterval = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $RepeatInterval
[System.TimeSpan] $RandomDelay = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $RandomDelay
[System.TimeSpan] $RepetitionDuration = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $RepetitionDuration -AllowIndefinitely
[System.TimeSpan] $IdleWaitTimeout = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $IdleWaitTimeout
[System.TimeSpan] $IdleDuration = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $IdleDuration
[System.TimeSpan] $ExecutionTimeLimit = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $ExecutionTimeLimit
[System.TimeSpan] $RestartInterval = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $RestartInterval
$currentValues = Get-CurrentResource -TaskName $TaskName -TaskPath $TaskPath
if ($Ensure -eq 'Present')
{
<#
If the scheduled task already exists and is enabled but it needs to be disabled
and the action executable isn't specified then disable the task
#>
if ($currentValues.Ensure -eq 'Present' `
-and $currentValues.Enable `
-and -not $Enable `
-and -not $PSBoundParameters.ContainsKey('ActionExecutable'))
{
Write-Verbose -Message ($script:localizedData.DisablingExistingScheduledTask -f $TaskName, $TaskPath)
Disable-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath
return
}
if ($RepetitionDuration -lt $RepeatInterval)
{
New-InvalidArgumentException `
-Message ($script:localizedData.RepetitionDurationLessThanIntervalError -f $RepetitionDuration, $RepeatInterval) `
-ArgumentName RepeatInterval
}
if ($ScheduleType -eq 'Daily' -and $DaysInterval -eq 0)
{
New-InvalidArgumentException `
-Message ($script:localizedData.DaysIntervalError -f $DaysInterval) `
-ArgumentName DaysInterval
}
if ($ScheduleType -eq 'Weekly' -and $WeeksInterval -eq 0)
{
New-InvalidArgumentException `
-Message ($script:localizedData.WeeksIntervalError -f $WeeksInterval) `
-ArgumentName WeeksInterval
}
if ($ScheduleType -eq 'Weekly' -and $DaysOfWeek.Count -eq 0)
{
New-InvalidArgumentException `
-Message ($script:localizedData.WeekDayMissingError) `
-ArgumentName DaysOfWeek
}
if ($ScheduleType -eq 'OnEvent' -and -not ([xml]$EventSubscription))
{
New-InvalidArgumentException `
-Message ($script:localizedData.OnEventSubscriptionError) `
-ArgumentName EventSubscription
}
if ($ExecuteAsGMSA -and ($ExecuteAsCredential -or $BuiltInAccount))
{
New-InvalidArgumentException `
-Message ($script:localizedData.gMSAandCredentialError) `
-ArgumentName ExecuteAsGMSA
}
if ($SynchronizeAcrossTimeZone -and ($ScheduleType -notin @('Once', 'Daily', 'Weekly')))
{
New-InvalidArgumentException `
-Message ($script:localizedData.SynchronizeAcrossTimeZoneInvalidScheduleType) `
-ArgumentName SynchronizeAcrossTimeZone
}
# Configure the action
$actionParameters = @{
Execute = $ActionExecutable
}
if ($ActionArguments)
{
$actionParameters.Add('Argument', $ActionArguments)
}
if ($ActionWorkingPath)
{
$actionParameters.Add('WorkingDirectory', $ActionWorkingPath)
}
$action = New-ScheduledTaskAction @actionParameters
$scheduledTaskArguments += @{
Action = $action
}
# Configure the settings
$settingParameters = @{
DisallowDemandStart = $DisallowDemandStart
DisallowHardTerminate = $DisallowHardTerminate
Compatibility = $Compatibility
AllowStartIfOnBatteries = $AllowStartIfOnBatteries
Disable = -not $Enable
Hidden = $Hidden
RunOnlyIfIdle = $RunOnlyIfIdle
DisallowStartOnRemoteAppSession = $DisallowStartOnRemoteAppSession
StartWhenAvailable = $StartWhenAvailable
DontStopIfGoingOnBatteries = $DontStopIfGoingOnBatteries
WakeToRun = $WakeToRun
RestartOnIdle = $RestartOnIdle
DontStopOnIdleEnd = $DontStopOnIdleEnd
MultipleInstances = $MultipleInstances
Priority = $Priority
RestartCount = $RestartCount
RunOnlyIfNetworkAvailable = $RunOnlyIfNetworkAvailable
}
if ($IdleDuration -gt [System.TimeSpan] '00:00:00')
{
$settingParameters.Add('IdleDuration', $IdleDuration)
}
if ($IdleWaitTimeout -gt [System.TimeSpan] '00:00:00')
{
$settingParameters.Add('IdleWaitTimeout', $IdleWaitTimeout)
}
if ($PSBoundParameters.ContainsKey('ExecutionTimeLimit'))
{
$settingParameters.Add('ExecutionTimeLimit', $ExecutionTimeLimit)
}
if ($RestartInterval -gt [System.TimeSpan] '00:00:00')
{
$settingParameters.Add('RestartInterval', $RestartInterval)
}
if (-not [System.String]::IsNullOrWhiteSpace($NetworkName))
{
$settingParameters.Add('NetworkName', $NetworkName)
}
$setting = New-ScheduledTaskSettingsSet @settingParameters
$scheduledTaskArguments += @{
Settings = $setting
}
<#
On Windows Server 2012 R2 setting a blank timespan for ExecutionTimeLimit
does not result in the PT0S timespan value being set. So set this
if it has not been set.
#>
if ($PSBoundParameters.ContainsKey('ExecutionTimeLimit') -and `
[System.String]::IsNullOrEmpty($setting.ExecutionTimeLimit))
{
$setting.ExecutionTimeLimit = 'PT0S'
}
# Configure the trigger
$triggerParameters = @{}
# A random delay is not supported when the scheduleType is set to OnEvent
if ($RandomDelay -gt [System.TimeSpan]::FromSeconds(0) -and $ScheduleType -ne 'OnEvent')
{
$triggerParameters.Add('RandomDelay', $RandomDelay)
}
switch ($ScheduleType)
{
'Once'
{
$triggerParameters.Add('Once', $true)
$triggerParameters.Add('At', $StartTime)
break
}
'Daily'
{
$triggerParameters.Add('Daily', $true)
$triggerParameters.Add('At', $StartTime)
$triggerParameters.Add('DaysInterval', $DaysInterval)
break
}
'Weekly'
{
$triggerParameters.Add('Weekly', $true)
$triggerParameters.Add('At', $StartTime)
if ($DaysOfWeek.Count -gt 0)
{
$triggerParameters.Add('DaysOfWeek', $DaysOfWeek)
}
if ($WeeksInterval -gt 0)
{
$triggerParameters.Add('WeeksInterval', $WeeksInterval)
}
break
}
'AtStartup'
{
$triggerParameters.Add('AtStartup', $true)
break
}
'AtLogOn'
{
$triggerParameters.Add('AtLogOn', $true)
if (-not [System.String]::IsNullOrWhiteSpace($User) -and $LogonType -ne 'Group')
{
$triggerParameters.Add('User', $User)
}
break
}
'OnEvent'
{
Write-Verbose -Message ($script:localizedData.ConfigureTaskEventTrigger -f $TaskName)
$cimTriggerClass = Get-CimClass -ClassName MSFT_TaskEventTrigger -Namespace Root/Microsoft/Windows/TaskScheduler:MSFT_TaskEventTrigger
$trigger = New-CimInstance -CimClass $cimTriggerClass -ClientOnly
$trigger.Enabled = $true
$trigger.Subscription = $EventSubscription
}
}
if ($ScheduleType -ne 'OnEvent')
{
$trigger = New-ScheduledTaskTrigger @triggerParameters -ErrorAction SilentlyContinue
}
if (-not $trigger)
{
New-InvalidOperationException `
-Message ($script:localizedData.TriggerCreationError) `
-ErrorRecord $_
}
if ($RepeatInterval -gt [System.TimeSpan]::Parse('0:0:0'))
{
# A repetition pattern is required so create it and attach it to the trigger object
Write-Verbose -Message ($script:localizedData.ConfigureTriggerRepetitionMessage)
if ($RepetitionDuration -le $RepeatInterval)
{
New-InvalidArgumentException `
-Message ($script:localizedData.RepetitionIntervalError -f $RepeatInterval, $RepetitionDuration) `
-ArgumentName RepetitionDuration
}
$tempTriggerParameters = @{
Once = $true
At = '6:6:6'
RepetitionInterval = $RepeatInterval
}
Write-Verbose -Message ($script:localizedData.CreateRepetitionPatternMessage)
switch ($trigger.GetType().FullName)
{
'Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger'
{
# This is the type of trigger object returned in Windows Server 2012 R2/Windows 8.1 and below
Write-Verbose -Message ($script:localizedData.CreateTemporaryTaskMessage)
$tempTriggerParameters.Add('RepetitionDuration', $RepetitionDuration)
# Create a temporary trigger and task and copy the repetition CIM object from the temporary task
$tempTrigger = New-ScheduledTaskTrigger @tempTriggerParameters
$tempTask = New-ScheduledTask -Action $action -Trigger $tempTrigger
# Store the repetition settings
$repetition = $tempTask.Triggers[0].Repetition
}
'Microsoft.Management.Infrastructure.CimInstance'
{
# This is the type of trigger object returned in Windows Server 2016/Windows 10 and above
Write-Verbose -Message ($script:localizedData.CreateTemporaryTriggerMessage)
if ($RepetitionDuration -gt [System.TimeSpan]::Parse('0:0:0') -and $RepetitionDuration -lt [System.TimeSpan]::MaxValue)
{
$tempTriggerParameters.Add('RepetitionDuration', $RepetitionDuration)
}
# Create a temporary trigger and copy the repetition CIM object from it to the actual trigger
$tempTrigger = New-ScheduledTaskTrigger @tempTriggerParameters
# Store the repetition settings
$repetition = $tempTrigger.Repetition
}
default
{
New-InvalidOperationException `
-Message ($script:localizedData.TriggerUnexpectedTypeError -f $trigger.GetType().FullName)
}
}
}
if ($trigger.GetType().FullName -eq 'Microsoft.Management.Infrastructure.CimInstance')
{
# On W2016+ / W10+ the Delay property is supported on the AtLogon, AtStartup and OnEvent trigger types
$triggerSupportsDelayProperty = @('AtLogon', 'AtStartup', 'OnEvent')
if ($ScheduleType -in $triggerSupportsDelayProperty)
{
$trigger.Delay = [System.Xml.XmlConvert]::ToString([System.TimeSpan]$Delay)
}
}
$scheduledTaskArguments += @{
Trigger = $trigger
}
# Prepare the register arguments
$registerArguments = @{}
$username = $null
if ($PSBoundParameters.ContainsKey('BuiltInAccount'))
{
<#
The validateset on BuiltInAccount has already checked the
non-null value to be 'LOCAL SERVICE', 'NETWORK SERVICE' or
'SYSTEM'
#>
$username = 'NT AUTHORITY\' + $BuiltInAccount
$registerArguments.Add('User', $username)
$LogonType = 'ServiceAccount'
}
elseif ($PSBoundParameters.ContainsKey('ExecuteAsGMSA'))
{
$username = $ExecuteAsGMSA
$LogonType = 'Password'
}
elseif ($PSBoundParameters.ContainsKey('ExecuteAsCredential'))
{
$username = $ExecuteAsCredential.UserName
# If the LogonType is not specified then set it to password
if ([System.String]::IsNullOrEmpty($LogonType))
{
$LogonType = 'Password'
}
if ($LogonType -ne 'Group')
{
$registerArguments.Add('User', $username)
}
if ($LogonType -notin ('Interactive', 'S4U', 'Group'))
{
# Only set the password if the LogonType is not interactive or S4U
$registerArguments.Add('Password', $ExecuteAsCredential.GetNetworkCredential().Password)
}
}
else
{
<#
'NT AUTHORITY\SYSTEM' basically gives the schedule task admin
privileges, should we default to 'NT AUTHORITY\LOCAL SERVICE'
instead?
#>
$username = 'NT AUTHORITY\SYSTEM'
$registerArguments.Add('User', $username)
$LogonType = 'ServiceAccount'
}
# Prepare the principal arguments
$principalArguments = @{
Id = 'Author'
}
if ($LogonType -eq 'Group')
{
$principalArguments.GroupId = $username
}
else
{
$principalArguments.LogonType = $LogonType
$principalArguments.UserId = $username
}
# Set the Run Level if defined
if ($PSBoundParameters.ContainsKey('RunLevel'))
{
$principalArguments.Add('RunLevel', $RunLevel)
}
# Create the principal object
Write-Verbose -Message ($script:localizedData.CreateScheduledTaskPrincipalMessage -f $username, $LogonType)
$principal = New-ScheduledTaskPrincipal @principalArguments
$scheduledTaskArguments += @{
Principal = $principal
}
$tempScheduledTask = New-ScheduledTask @scheduledTaskArguments -ErrorAction Stop
if ($currentValues.Ensure -eq 'Present')
{
Write-Verbose -Message ($script:localizedData.RetrieveScheduledTaskMessage -f $TaskName, $TaskPath)
$tempScheduledTask = New-ScheduledTask @scheduledTaskArguments -ErrorAction Stop
$scheduledTask = ScheduledTasks\Get-ScheduledTask `
-TaskName $currentValues.TaskName `
-TaskPath $currentValues.TaskPath `
-ErrorAction Stop
$scheduledTask.Actions = $action
$scheduledTask.Triggers = $tempScheduledTask.Triggers
$scheduledTask.Settings = $setting
$scheduledTask.Principal = $principal
}
else
{
$scheduledTask = $tempScheduledTask
}
Write-Verbose -Message ($script:localizedData.CreateNewScheduledTaskMessage -f $TaskName, $TaskPath)
if ($repetition)
{
Write-Verbose -Message ($script:localizedData.SetRepetitionTriggerMessage -f $TaskName, $TaskPath)
$scheduledTask.Triggers[0].Repetition = $repetition
}
if (-not [System.String]::IsNullOrWhiteSpace($Description))
{
$scheduledTask.Description = $Description
}
if ($scheduledTask.Triggers[0].StartBoundary)
{
<#
The way New-ScheduledTaskTrigger writes the StartBoundary has issues because it does not take
the setting "Synchronize across time zones" in consideration. What happens if synchronize across
time zone is enabled in the scheduled task GUI is that the time is written like this:
2018-09-27T18:45:08+02:00
When the setting synchronize across time zones is disabled, the time is written as:
2018-09-27T18:45:08
The problem in New-ScheduledTaskTrigger is that it always writes the time the format that
includes the full timezone offset (W2016 behaviour, W2012R2 does it the other way around).
Which means "Synchronize across time zones" is enabled by default on W2016 and disabled by
default on W2012R2. To prevent that, we are overwriting the StartBoundary here to insert
the time in the format we want it, so we can enable or disable "Synchronize across time zones".
#>
$scheduledTask.Triggers[0].StartBoundary = Get-DateTimeString -Date $StartTime -SynchronizeAcrossTimeZone $SynchronizeAcrossTimeZone
}
if ($currentValues.Ensure -eq 'Present')
{
# Updating the scheduled task
Write-Verbose -Message ($script:localizedData.UpdateScheduledTaskMessage -f $TaskName, $TaskPath)
$null = Set-ScheduledTask -InputObject $scheduledTask @registerArguments
}
else
{
Write-Verbose -Message ($script:localizedData.CreateNewScheduledTaskMessage -f $TaskName, $TaskPath)
# Register the scheduled task
$registerArguments.Add('TaskName', $TaskName)
$registerArguments.Add('TaskPath', $TaskPath)
$registerArguments.Add('InputObject', $scheduledTask)
$null = Register-ScheduledTask @registerArguments
}
}
if ($Ensure -eq 'Absent')
{
Write-Verbose -Message ($script:localizedData.RemoveScheduledTaskMessage -f $TaskName, $TaskPath)
Unregister-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -Confirm:$false -ErrorAction Stop
}
}
<#
.SYNOPSIS
Tests if the current resource state matches the desired resource state.
.PARAMETER TaskName
The name of the task.
.PARAMETER TaskPath
The path to the task - defaults to the root directory.
.PARAMETER Description
The task description.
.PARAMETER ActionExecutable
The path to the .exe for this task.
.PARAMETER ActionArguments
The arguments to pass the executable.
.PARAMETER ActionWorkingPath
The working path to specify for the executable.
.PARAMETER ScheduleType
When should the task be executed.
.PARAMETER RepeatInterval
How many units (minutes, hours, days) between each run of this task?
.PARAMETER StartTime
The time of day this task should start at - defaults to 12:00 AM. Not valid for
AtLogon and AtStartup tasks.
.PARAMETER SynchronizeAcrossTimeZone
Enable the scheduled task option to synchronize across time zones. This is enabled
by including the timezone offset in the scheduled task trigger. Defaults to false
which does not include the timezone offset.
.PARAMETER Ensure
Present if the task should exist, Absent if it should be removed.
.PARAMETER Enable
True if the task should be enabled, false if it should be disabled.
.PARAMETER BuiltInAccount
Run the task as one of the built in service accounts.
When set ExecuteAsCredential will be ignored and LogonType will be set to 'ServiceAccount'
.PARAMETER ExecuteAsCredential
The credential this task should execute as. If not specified defaults to running
as the local system account. Cannot be used in combination with ExecuteAsGMSA.
.PARAMETER ExecuteAsGMSA
The gMSA (Group Managed Service Account) this task should execute as. Cannot be
used in combination with ExecuteAsCredential.
.PARAMETER DaysInterval
Specifies the interval between the days in the schedule. An interval of 1 produces
a daily schedule. An interval of 2 produces an every-other day schedule.
.PARAMETER RandomDelay
Specifies a random amount of time to delay the start time of the trigger. The
delay time is a random time between the time the task triggers and the time that
you specify in this setting.
.PARAMETER RepetitionDuration
Specifies how long the repetition pattern repeats after the task starts.
.PARAMETER DaysOfWeek
Specifies an array of the days of the week on which Task Scheduler runs the task.
.PARAMETER WeeksInterval