forked from stcu/SharedScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvertTo-ICalendar.ps1
293 lines (263 loc) · 10.4 KB
/
ConvertTo-ICalendar.ps1
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
<#
.SYNOPSIS
Converts supported objects (Scheduled Tasks) to the RFC 5545 iCalendar format.
.DESCRIPTION
This converts the schedule of a Scheduled Task to a format that can be parsed by calendar apps,
allowing for debugging a schedule, correlating to errors and resource shortages, and examining
job distribution over time.
.INPUTS
Microsoft.Management.Infrastructure.CimInstance of CIM class MSFT_ScheduledTask, as
returned by Get-ScheduledTask.
.OUTPUTS
System.String containing iCalendar data.
.FUNCTIONALITY
Scheduled Tasks
.LINK
http://webcoder.info/recurrence.html
.LINK
https://datatracker.ietf.org/doc/html/rfc5545
.LINK
https://wutils.com/wmi/root/microsoft/windows/taskscheduler/msft_scheduledtask/
.LINK
https://docs.microsoft.com/windows-server/administration/windows-commands/schtasks-query
.LINK
https://docs.microsoft.com/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc725744%28v=ws.11%29
.LINK
Use-Command.ps1
.LINK
ConvertFrom-CimInstance.ps1
.LINK
ConvertFrom-XmlElement.ps1
.LINK
New-ScheduledTaskTrigger
.LINK
Get-Date
.EXAMPLE
Get-ScheduledTask -TaskPath \ |ConvertTo-ICalendar.ps1 |Out-File tasks.ics utf8
Creates file tasks.ics to import into Google Calendar, iCalendar, or Outlook to review job schedules.
#>
#Requires -Version 7
#Requires -Modules ScheduledTasks
[CmdletBinding()][OutputType([string])] Param(
# A CimInstance of MSFT_ScheduledTask, as output by Get-ScheduledTask.
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({$_.CimClass.CimClassName -eq 'MSFT_ScheduledTask'})]
[Microsoft.Management.Infrastructure.CimInstance] $ScheduledTask,
# The time zone to use in the iCalendar data.
[ValidateScript({$_.HasIanaId})][TimeZoneInfo] $TimeZone = (Get-TimeZone |ForEach-Object {[string]$tzid = 'UTC'
[void][TimeZoneInfo]::TryConvertWindowsIdToIanaId($_.Id, [ref]$tzid); Get-TimeZone -Id $tzid}),
# For tasks without an explicit duration, use this as the duration in the iCalendar events.
[TimeSpan] $DefaultTaskDuration = '00:01:00'
)
Begin
{
Use-Command.ps1 schtasks C:\windows\system32\schtasks.exe -Message 'Unable to locate schtasks.exe'
Set-Variable MonthNames ((Get-Culture -Name '').DateTimeFormat.MonthGenitiveNames) `
-Scope Script -Option Constant -Description 'Month names, invariant culture'
filter ConvertTo-DateTimeStamp
{
[CmdletBinding()][OutputType([string])] Param([Parameter(ValueFromPipelineByPropertyName=$true)][psobject]$Date)
if($null -eq $Date) {Get-Date (Get-Date).ToUniversalTime() -f yyyyMMdd\THHmmssZ}
else {Get-Date (Get-Date $Date).ToUniversalTime() -f yyyyMMdd\THHmmssZ}
}
function ConvertTo-DateTimeWithZone
{
[CmdletBinding()][OutputType([string])] Param(
[datetime] $Value,
[TimeZoneInfo] $TimeZone
)
return "TZID=$($TimeZone.Id):$(Get-Date $value -f yyyyMMdd\THHmmss)"
}
function ConvertFrom-SimpleInterval
{
[CmdletBinding()][OutputType([string])] Param(
[ValidatePattern('\AP\d+[YMD]|T\d+[HMS]\z',ErrorMessage='A simple (single-unit) ISO8601 duration is required')]
[Parameter(Position=0,Mandatory=$true)][string] $Interval
)
$Interval -match '\d+' |Out-Null
[int] $value = $Matches[0]
$frequency = switch -Regex ($Interval)
{
'P\d+Y' {'YEARLY'}
'P\d+M' {'MONTHLY'}
'P\d+D' {'DAILY'}
'PT\d+H' {'HOURLY'}
'PT\d+M' {'MINUTELY'}
'PT\d+S' {'SECONDLY'}
}
return "`r`nRRULE:FREQ=$frequency;INTERVAL=$value"
}
function ConvertFrom-TaskDailyTrigger
{
[CmdletBinding()][OutputType([string])] Param(
[Parameter(Mandatory=$true)][ValidateScript({$_.CimClass.CimClassName -eq 'MSFT_TaskDailyTrigger'})]
[Microsoft.Management.Infrastructure.CimInstance] $TaskTrigger
)
return "`r`nRRULE:FREQ=DAILY;INTERVAL=$($TaskTrigger.DaysInterval)"
}
function ConvertFrom-TaskWeeklyTrigger
{
[CmdletBinding()][OutputType([string])] Param(
[Parameter(Mandatory=$true)]
[ValidateScript({$_.CimClass.CimClassName -eq 'MSFT_TaskWeeklyTrigger'})]
[Microsoft.Management.Infrastructure.CimInstance] $TaskTrigger
)
if($TaskTrigger.DaysOfWeek -in 0,0x7F)
{
return "`r`nRRULE:FREQ=WEEKLY;INTERVAL=$($TaskTrigger.WeeksInterval)"
}
else
{
$byday = @(switch($TaskTrigger.DaysOfWeek)
{
{$_ -band 0x01}{'SU'}
{$_ -band 0x02}{'MO'}
{$_ -band 0x04}{'TU'}
{$_ -band 0x08}{'WE'}
{$_ -band 0x10}{'TH'}
{$_ -band 0x20}{'FR'}
{$_ -band 0x40}{'SA'}
}) -join ','
return "`r`nRRULE:FREQ=WEEKLY;INTERVAL=$($TaskTrigger.WeeksInterval);BYDAY=$byday"
}
}
function ConvertFrom-TaskMonthlyDOWTrigger
{
[CmdletBinding()][OutputType([string])] Param(
[Parameter(Mandatory=$true)][ValidateScript({$_.CimClass.CimClassName -eq 'MSFT_TaskMonthlyDOWTrigger'})]
[Microsoft.Management.Infrastructure.CimInstance] $TaskTrigger
)
return "`r`nRRULE:FREQ=MONTHLY;BYDAY=$($TaskTrigger.DaysOfWeek)"
}
function ConvertFrom-TaskMonthlyTrigger
{
[CmdletBinding()][OutputType([string])] Param(
[Parameter(Mandatory=$true)][ValidateScript({$_.CimClass.CimClassName -eq 'MSFT_TaskMonthlyTrigger'})]
[Microsoft.Management.Infrastructure.CimInstance] $TaskTrigger
)
return "`r`nRRULE:FREQ=MONTHLY;BYMONTHDAY=$($TaskTrigger.DaysOfMonth)"
}
filter ConvertFrom-ScheduleByMonth
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter','',
Justification='Script analysis is missing the usage of Months.')]
[CmdletBinding()][OutputType([string])] Param(
[Parameter(ValueFromPipelineByPropertyName=$true)][psobject] $Months,
[Parameter(ValueFromPipelineByPropertyName=$true)][psobject] $DaysOfMonth
)
[int[]] $monthNums = 1..12 |Where-Object {$Months.PSObject.Properties.Match($MonthNames[$_-1])}
$days = switch("$($DaysOfMonth.Day)"){Last{'BYSETPOS=-1'}default{"BYDAY=$($DaysOfMonth.Day -join ',')"}}
if($monthNums.Count -eq 12)
{
return "`r`nRRULE:FREQ=MONTHLY;INTERVAL=1;$days"
}
else
{
return "`r`nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=$($monthNums -join ',');$days"
}
}
filter ConvertFrom-ScheduleByMonthDayOfWeek
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter','',
Justification='Script analysis is missing the usage of Months.')]
[CmdletBinding()][OutputType([string])] Param(
[Parameter(ValueFromPipelineByPropertyName=$true)][psobject] $Months,
[Parameter(ValueFromPipelineByPropertyName=$true)][psobject] $Weeks,
[Parameter(ValueFromPipelineByPropertyName=$true)][psobject] $DaysOfWeek
)
[int[]] $monthNums = 1..12 |Where-Object {$Months.PSObject.Properties.Match($MonthNames[$_-1])}
$pos = @(switch($Weeks.Week){Last{-1}default{$_}})
$days = $DaysOfWeek.PSObject.Properties.Match('*').Name |
ForEach-Object {$_.Substring(0,3).ToUpperInvariant()}
$posdays = "BYDAY=$((Format-Permutations.ps1 -Format '{0}{1}' -InputObject $pos,$days) -join ',')"
if($posdays -eq 'BYDAY=Last') {$posdays = 'BYSETPOS=-1'}
if($monthNums.Count -eq 12)
{
return "`r`nRRULE:FREQ=MONTHLY;INTERVAL=1;$posdays"
}
else
{
return "`r`nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=$($monthNums -join ',');$posdays"
}
}
filter ConvertFrom-TaskTrigger
{
[CmdletBinding()] Param(
[Parameter(Position=0,Mandatory=$true)][string] $TaskName,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({$_.CimClass.CimClassName -like 'MSFT_Task*Trigger'})]
[Microsoft.Management.Infrastructure.CimInstance] $TaskTrigger,
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('StartBoundary')][datetime] $Start,
[TimeSpan] $DefaultTaskDuration,
[TimeZoneInfo] $TimeZone
)
if(!$TaskTrigger.Enabled) {Write-Warning "Disabled $($TaskTrigger.CimClass.CimClassName) will be ignored"; return}
$end = $null -eq $TaskTrigger.Repetition.Duration ? $Start.Add($DefaultTaskDuration) :
$Start.Add([Xml.XmlConvert]::ToTimeSpan($TaskTrigger.Repetition.Duration))
$schedule = @"
DTSTART;$(ConvertTo-DateTimeWithZone -Value $Start -TimeZone $TimeZone)
DTEND;$(ConvertTo-DateTimeWithZone -Value $end -TimeZone $TimeZone)
"@
switch($TaskTrigger.CimClass.CimClassName)
{
MSFT_TaskDailyTrigger {$schedule += ConvertFrom-TaskDailyTrigger $TaskTrigger}
MSFT_TaskWeeklyTrigger {$schedule += ConvertFrom-TaskWeeklyTrigger $TaskTrigger}
# MSFT_TaskMonthlyDOWTrigger {$schedule += ConvertFrom-TaskMonthlyDOWTrigger $TaskTrigger}
# MSFT_TaskMonthlyTrigger {$schedule += ConvertFrom-TaskMonthlyTrigger $TaskTrigger}
{$_ -eq 'MSFT_TaskTimeTrigger' -and $null -ne $TaskTrigger.Repetition.Interval}
{$schedule += ConvertFrom-SimpleInterval $TaskTrigger.Repetition.Interval}
MSFT_TaskTrigger
{
Write-Verbose "CIM object contains no useful scheduling data; reading via schtasks XML"
$task = [xml](schtasks /query /xml /tn $TaskName) |ConvertFrom-XmlElement.ps1
$task.Triggers |
Where-Object {$_.PSObject.Properties.Match('CalendarTrigger').Count -eq 0} |
ConvertTo-Json -Compress -Depth 5 |
ForEach-Object {Write-Warning "Ignoring non-calendar trigger: $_"}
$calendarTrigger = @($task.Triggers |
Where-Object {$_.PSObject.Properties.Match('CalendarTrigger').Count -gt 0} |
Select-Object -ExpandProperty CalendarTrigger)
$calendarTrigger |
Where-Object {$_.PSObject.Properties.Match('ScheduleByMonth*').Count -eq 0} |
ConvertTo-Json -Compress -Depth 5 |
ForEach-Object {Write-Warning "Ignoring non-month calendar trigger: $_"}
$schedule += $calendarTrigger |
Where-Object {$_.PSObject.Properties.Match('ScheduleByMonth').Count -gt 0} |
Select-Object -ExpandProperty ScheduleByMonth |
ConvertFrom-ScheduleByMonth
$schedule += $calendarTrigger |
Where-Object {$_.PSObject.Properties.Match('ScheduleByMonthDayOfWeek').Count -gt 0} |
Select-Object -ExpandProperty ScheduleByMonthDayOfWeek |
ConvertFrom-ScheduleByMonthDayOfWeek
}
default {Write-Warning "$_ will be ignored"}
}
return $schedule
}
$ical = @"
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//webcoder.info//$($MyInvocation.MyCommand.Name)//EN
"@
}
Process
{
$ical += @"
BEGIN:VEVENT
UID:$(New-Guid)
DTSTAMP:$($ScheduledTask |ConvertTo-DateTimeStamp)
$($ScheduledTask.Triggers |ConvertFrom-TaskTrigger -TaskName $ScheduledTask.TaskName `
-DefaultTaskDuration $DefaultTaskDuration -TimeZone $TimeZone)
SUMMARY:$($ScheduledTask.TaskName)
DESCRIPTION:$($ScheduledTask.Description)
END:VEVENT
"@
}
End
{
$ical += @"
END:VCALENDAR
"@
return $ical
}