-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathAdd-CIPPScheduledTask.ps1
More file actions
320 lines (284 loc) · 15 KB
/
Add-CIPPScheduledTask.ps1
File metadata and controls
320 lines (284 loc) · 15 KB
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
function Add-CIPPScheduledTask {
[CmdletBinding()]
param(
[Parameter(Mandatory = $false)]
[pscustomobject]$Task,
[Parameter(Mandatory = $false)]
[bool]$Hidden,
[Parameter(Mandatory = $false)]
$DisallowDuplicateName = $false,
[Parameter(Mandatory = $false)]
[string]$SyncType = $null,
[Parameter(Mandatory = $false)]
[switch]$RunNow,
[Parameter(Mandatory = $false)]
[string]$RowKey = $null,
[Parameter(Mandatory = $false)]
[string]$DesiredStartTime = $null,
[Parameter(Mandatory = $false)]
$Headers
)
try {
$Table = Get-CIPPTable -TableName 'ScheduledTasks'
if ($RunNow.IsPresent -and $RowKey) {
try {
$Filter = "PartitionKey eq 'ScheduledTask' and RowKey eq '$($RowKey)'"
$ExistingTask = (Get-CIPPAzDataTableEntity @Table -Filter $Filter)
$ExistingTask.ScheduledTime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds
$ExistingTask.TaskState = 'Planned'
Add-CIPPAzDataTableEntity @Table -Entity $ExistingTask -Force
Write-LogMessage -headers $Headers -API 'RunNow' -message "Task $($ExistingTask.Name) scheduled to run now" -Sev 'Info' -Tenant $ExistingTask.Tenant
Add-CippQueueMessage -Cmdlet 'Start-UserTasksOrchestrator' -Parameters @{
TaskId = $RowKey
}
return "Task $($ExistingTask.Name) scheduled to run now"
} catch {
$ErrorMessage = Get-NormalizedError -Message $_.Exception.Message
Write-LogMessage -headers $Headers -API 'RunNow' -message "Could not run task: $ErrorMessage" -Sev 'Error'
return "Could not run task: $ErrorMessage"
}
} else {
if (!$Task.RowKey) {
$RowKey = (New-Guid).Guid
} else {
$RowKey = $Task.RowKey
}
if ($DisallowDuplicateName) {
$Filter = "PartitionKey eq 'ScheduledTask' and Name eq '$($Task.Name)' and TaskState ne 'Completed' and TaskState ne 'Failed'"
$ExistingTask = (Get-CIPPAzDataTableEntity @Table -Filter $Filter)
if ($ExistingTask) {
return "Task with name $($Task.Name) already exists"
}
}
$propertiesToCheck = @('Webhook', 'Email', 'PSA')
$PostExecutionObject = ($propertiesToCheck | Where-Object { $task.PostExecution.$_ -eq $true })
$PostExecution = $PostExecutionObject ? @($PostExecutionObject -join ',') : ($Task.PostExecution.value -join ',')
$Parameters = [System.Collections.Hashtable]@{}
foreach ($Key in $task.Parameters.PSObject.Properties.Name) {
$Param = $task.Parameters.$Key
if ($null -eq $Param -or $Param -eq '' -or ($Param | Measure-Object).Count -eq 0) {
continue
}
# handle different object types in params
if ($Param -is [System.Collections.IDictionary] -or $Param[0].Key) {
Write-Information "Parameter $Key is a hashtable"
$ht = @{}
foreach ($p in $Param.GetEnumerator()) {
$ht[$p.Key] = $p.Value
}
$Parameters[$Key] = [PSCustomObject]$ht
Write-Information "Converted $Key to PSObject $($Parameters[$Key] | ConvertTo-Json -Compress)"
} elseif ($Param -is [System.Object[]] -and -not ($Param -is [string])) {
Write-Information "Parameter $Key is an enumerable object"
$Param = $Param | ForEach-Object {
if ($null -eq $_) {
# Skip null entries
return
}
if ($_ -is [System.Collections.IDictionary]) {
[PSCustomObject]$_
} elseif ($_ -is [PSCustomObject]) {
$_
} else {
$_
}
} | Where-Object { $null -ne $_ }
$Parameters[$Key] = $Param
} else {
Write-Information "Parameter $Key is a simple value"
$Parameters[$Key] = $Param
}
}
if ($Headers) {
$Parameters.Headers = $Headers | Select-Object -Property 'x-forwarded-for', 'x-ms-client-principal', 'x-ms-client-principal-idp', 'x-ms-client-principal-name'
}
$Parameters = ($Parameters | ConvertTo-Json -Depth 10 -Compress)
$AdditionalProperties = [System.Collections.Hashtable]@{}
foreach ($Prop in $task.AdditionalProperties) {
if ($null -eq $Prop.Value -or $Prop.Value -eq '' -or ($Prop.Value | Measure-Object).Count -eq 0) {
continue
}
$AdditionalProperties[$Prop.Key] = $Prop.Value
}
$AdditionalProperties = ([PSCustomObject]$AdditionalProperties | ConvertTo-Json -Compress)
if ($Parameters -eq 'null') { $Parameters = '' }
$Recurrence = if ([string]::IsNullOrEmpty($task.Recurrence.value)) {
$task.Recurrence
} else {
$task.Recurrence.value
}
if ($task.PSObject.Properties.Name -notcontains 'ScheduledTime') {
$task | Add-Member -MemberType NoteProperty -Name 'ScheduledTime' -Value 0 -Force
}
if ($DesiredStartTime) {
try {
# Parse the epoch time
$epochSeconds = [int64]$DesiredStartTime
# Set ScheduledTime to the desired time
$task.ScheduledTime = $epochSeconds
} catch {
Write-Warning "Failed to parse DesiredStartTime: $DesiredStartTime. Using provided ScheduledTime."
# Fall back to default
if ([int64]$task.ScheduledTime -eq 0 -or [string]::IsNullOrEmpty($task.ScheduledTime)) {
$task.ScheduledTime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds
}
}
} else {
# No DesiredStartTime - use current behavior (immediate execution)
if ([int64]$task.ScheduledTime -eq 0 -or [string]::IsNullOrEmpty($task.ScheduledTime)) {
$task.ScheduledTime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds
}
}
$excludedTenants = if ($task.excludedTenants.value) {
$task.excludedTenants.value -join ','
}
# Handle tenant filter - support both single tenant and tenant groups
$tenantFilter = $task.TenantFilter.value ? $task.TenantFilter.value : $task.TenantFilter
$originalTenantFilter = $task.TenantFilter
# If tenant filter is a complex object (from form), extract the value
if ($tenantFilter -is [PSCustomObject] -and $tenantFilter.value) {
$originalTenantFilter = $tenantFilter
$tenantFilter = $tenantFilter.value
}
# If tenant filter is a string but still seems to be JSON, try to parse it
if ($tenantFilter -is [string] -and $tenantFilter.StartsWith('{')) {
try {
$parsedTenantFilter = $tenantFilter | ConvertFrom-Json
if ($parsedTenantFilter.value) {
$originalTenantFilter = $parsedTenantFilter
$tenantFilter = $parsedTenantFilter.value
}
} catch {
# If parsing fails, use the string as is
Write-Warning "Could not parse tenant filter JSON: $tenantFilter"
}
}
$entity = @{
PartitionKey = [string]'ScheduledTask'
TaskState = [string]'Planned'
RowKey = [string]$RowKey
Tenant = [string]$tenantFilter
excludedTenants = [string]$excludedTenants
Name = [string]$task.Name
Command = [string]$task.Command.value
Parameters = [string]$Parameters
ScheduledTime = [string]$task.ScheduledTime
Recurrence = [string]$Recurrence
PostExecution = [string]$PostExecution
Reference = [string]$task.Reference
AdditionalProperties = [string]$AdditionalProperties
Hidden = [bool]$Hidden
Results = 'Planned'
AlertComment = [string]$task.AlertComment
CustomSubject = [string]$task.CustomSubject
}
# Always store DesiredStartTime if provided
if ($DesiredStartTime) {
$entity['DesiredStartTime'] = [string]$DesiredStartTime
}
# Store the original tenant filter for group expansion during execution
if ($originalTenantFilter -is [PSCustomObject] -and $originalTenantFilter.type -eq 'Group') {
$entity['TenantGroup'] = [string]($originalTenantFilter | ConvertTo-Json -Compress)
} elseif ($originalTenantFilter -is [string] -and $originalTenantFilter.StartsWith('{')) {
# Check if it's a serialized group object
try {
$parsedOriginal = $originalTenantFilter | ConvertFrom-Json
if ($parsedOriginal.type -eq 'Group') {
$entity['TenantGroup'] = [string]$originalTenantFilter
}
} catch {
# Not a JSON object, ignore
}
}
if ($task.Trigger) {
$entity.Trigger = [string]($task.Trigger | ConvertTo-Json -Compress)
$TriggerType = $task.Trigger.Type.value ?? $task.Trigger.Type
if ($TriggerType -eq 'DeltaQuery') {
$Parameters = @{}
if ($task.Trigger.WatchedAttributes -and ($task.Trigger.WatchedAttributes | Measure-Object).Count -gt 0) {
$Parameters.'$select' = $task.Trigger.WatchedAttributes | ForEach-Object { $_.value ?? $_ } -join ','
}
if ($task.Trigger.ResourceFilter) {
$ResourceFilterValues = $task.Trigger.ResourceFilter | ForEach-Object { $_.value ?? $_ }
$Parameters.'$filter' = "id eq '" + ($ResourceFilterValues -join "' or id eq '") + "'"
}
$Resource = $task.Trigger.DeltaResource.value ?? $task.Trigger.DeltaResource
if ($entity.TenantGroup) {
$tenantFilter = $entity.TenantGroup | ConvertFrom-Json
}
$DeltaQuery = @{
TenantFilter = $tenantFilter
Resource = $Resource
Parameters = $Parameters
PartitionKey = $RowKey
}
try {
$null = New-GraphDeltaQuery @DeltaQuery
Write-Information "Created delta query for resource $($Resource)"
} catch {
Write-Warning "Failed to create delta query for resource $($Resource): $($_.Exception.Message)"
}
}
}
if ($SyncType) {
$entity.SyncType = $SyncType
}
try {
Add-CIPPAzDataTableEntity @Table -Entity $entity -Force
} catch {
$ErrorMessage = Get-NormalizedError -Message $_.Exception.Message
Write-Information $_.InvocationInfo.PositionMessage
Write-Information ($entity | ConvertTo-Json)
return "Error - Could not add task: $ErrorMessage"
}
Write-LogMessage -headers $Headers -API 'ScheduledTask' -message "Added task $($entity.Name) with ID $($entity.RowKey)" -Sev 'Info' -Tenant $tenantFilter
# Calculate relative time for next run
$scheduledEpoch = [int64]$entity.ScheduledTime
$currentTime = [datetime]::UtcNow
if ($scheduledEpoch -eq 0 -or $scheduledEpoch -le ([int64](($currentTime) - (Get-Date '1/1/1970')).TotalSeconds)) {
# Task will run at next 15-minute interval - calculate efficiently
$minutesToAdd = 15 - ($currentTime.Minute % 15)
$nextRunTime = $currentTime.AddMinutes($minutesToAdd).AddSeconds(-$currentTime.Second).AddMilliseconds(-$currentTime.Millisecond)
$timeUntilRun = $nextRunTime - $currentTime
} else {
# Task is scheduled for a specific time in the future
$scheduledTime = [datetime]'1/1/1970' + [TimeSpan]::FromSeconds($scheduledEpoch)
$timeUntilRun = $scheduledTime - $currentTime
}
# Format relative time
$relativeTime = switch ($timeUntilRun.TotalMinutes) {
{ $_ -ge 1440 } {
$days = [Math]::Floor($timeUntilRun.TotalDays)
$hours = $timeUntilRun.Hours
$result = "$days day$(if ($days -ne 1) { 's' })"
if ($hours -gt 0) { $result += " and $hours hour$(if ($hours -ne 1) { 's' })" }
$result
break
}
{ $_ -ge 60 } {
$hours = [Math]::Floor($timeUntilRun.TotalHours)
$minutes = $timeUntilRun.Minutes
$result = "$hours hour$(if ($hours -ne 1) { 's' })"
if ($minutes -gt 0) { $result += " and $minutes minute$(if ($minutes -ne 1) { 's' })" }
$result
break
}
{ $_ -ge 2 } { "about $([Math]::Round($_)) minutes"; break }
{ $_ -ge 1 } { 'about 1 minute'; break }
default { 'less than a minute' }
}
if ($RunNow.IsPresent) {
Add-CippQueueMessage -Cmdlet 'Start-UserTasksOrchestrator' -Parameters @{
TaskId = $RowKey
}
return "Task $($entity.Name) scheduled to run now"
}
return "Successfully added task: $($entity.Name). It will run in $relativeTime."
}
} catch {
Write-Warning "Failed to add scheduled task: $($_.Exception.Message)"
$ErrorMessage = Get-NormalizedError -Message $_.Exception.Message
#Write-Information ($Task | ConvertTo-Json)
throw "Error - Could not add task: $ErrorMessage"
}
}