-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathConvert-ScheduledTasksToJobs.ps1
270 lines (249 loc) · 9.76 KB
/
Convert-ScheduledTasksToJobs.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
<#
.SYNOPSIS
Converts Scheduled Tasks to Scheduled Jobs.
.LINK
ConvertFrom-XmlElement.ps1
.LINK
Use-ReasonableDefaults.ps1
.LINK
Register-ScheduledJob
.LINK
New-ScheduledJobOption
.LINK
New-JobTrigger
.LINK
Disable-ScheduledTask
.LINK
Get-ScheduledTask
.LINK
Export-ScheduledTask
.LINK
Get-Credential
.LINK
Select-Xml
.LINK
ConvertTo-Json
.EXAMPLE
Convert-ScheduledTasksToJobs.ps1
Converts PowerShell Scheduled Tasks in the \ path to Scheduled Jobs.
#>
#Requires -Version 5
#Requires -RunAsAdministrator
#Requires -Modules PSScheduledJob
using namespace System.Xml
[CmdletBinding(SupportsShouldProcess=$true)][OutputType([void])] Param(
# Specifies the task path to export from.
[Parameter(Position=0)][string]$TaskPath = '\'
)
Use-ReasonableDefaults.ps1
function ConvertTo-TimeSpan([Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)][string]$Value)
{
[XmlConvert]::ToTimeSpan($Value)
}
function Convert-XmlElementToJson([Parameter(Position=0,Mandatory=$true)][XmlElement]$XmlElement)
{
$XmlElement |ConvertFrom-XmlElement.ps1 |ConvertTo-Json -Compress
}
function ConvertTo-JobTrigger
{
[CmdletBinding(SupportsShouldProcess=$true)] Param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)][XmlElement]$Trigger
)
Process
{
$params = @{}
if($Trigger.RandomDelay) { $params += @{ RandomDelay = ConvertTo-TimeSpan $Trigger.RandomDelay } }
if($Trigger.Enabled -and !([bool]::Parse($Trigger.Enabled))) { Write-Warning "Trigger is disabled"; return }
switch($Trigger.Name)
{
BootTrigger
{
$params += @{ AtStartup = $true }
}
CalendarTrigger
{
$params += @{ At = Get-Date $Trigger.StartBoundary }
switch((Select-Xml '*[starts-with(name(),"ScheduleBy")]' $Trigger).Node.Name)
{
ScheduleByDay
{
$params += @{ Daily = $true }
if($Trigger.ScheduleByDay.DaysInterval)
{
$params += @{ DaysInterval = $Trigger.ScheduleByDay.DaysInterval }
}
}
ScheduleByMonth
{
Write-Warning "Unable to schedule monthly task trigger: $(Convert-XmlElementToJson $Trigger)"
return
}
ScheduleByMonthDayOfWeek
{
Write-Warning "Unable to schedule day of month task trigger: $(Convert-XmlElementToJson $Trigger)"
return
}
ScheduleByWeek
{
$params += @{
Weekly = $true
DaysOfWeek = Select-Xml * $Trigger.ScheduleByWeek.DaysOfWeek |ForEach-Object {$_.Node.Name}
}
if($Trigger.ScheduleByWeek.WeeksInterval)
{
$params += @{ WeeksInterval = $Trigger.ScheduleByWeek.WeeksInterval }
}
}
default
{
Write-Warning "Unable to schedule calendar trigger: $(Convert-XmlElementToJson $Trigger)"
return
}
}
}
LogonTrigger
{
$params += @{ AtLogOn = $true }
if($Trigger.LogonTrigger.UserId)
{
$params += @{ UserId = $Trigger.LogonTrigger.UserId }
}
}
TimeTrigger
{
$params += @{ Once = $true; At = Get-Date $Trigger.StartBoundary }
if($Trigger.Repetition)
{
$params += @{ RepetitionInterval = ConvertTo-TimeSpan $Trigger.Repetition.Interval }
if($Trigger.Repetition.Duration)
{
$params += @{ RepetitionDuration = ConvertTo-TimeSpan $Trigger.Repetition.Duration }
}
else
{
$params += @{ RepeatIndefinitely = $true }
}
}
}
default
{
Write-Warning "Unable to schedule trigger: $(Convert-XmlElementToJson $Trigger)"
return
}
}
Write-Verbose "Create trigger: $(ConvertTo-Json $params -Compress)"
New-JobTrigger @params
}
}
$CredentialCache = @{}
function Convert-ScheduledTaskToJob
{
[CmdletBinding(SupportsShouldProcess=$true)] Param(
[Parameter(Position=0,Mandatory=$true)][ciminstance]$Task,
[Parameter(Position=1,Mandatory=$true)]$Script,
[Parameter(Position=2)][string]$Argument
)
[string]$userid = $Task.Principal.UserId
if(!$CredentialCache.ContainsKey($userid)) {$CredentialCache[$userid] = Get-Credential $userid}
$options = @{
ContinueIfGoingOnBattery = !$Task.Settings.StopIfGoingOnBatteries
DoNotAllowDemandStart = !$Task.Settings.AllowDemandStart
HideInTaskScheduler = $Task.Settings.Hidden
MultipleInstancePolicy = $Task.Settings.MultipleInstances
RequireNetwork = $Task.Settings.RunOnlyIfNetworkAvailable
RunElevated = $Task.Principal.RunLevel -eq 'Highest'
StartIfIdle = $Task.Settings.RunOnlyIfIdle
StartIfOnBattery = !$Task.Settings.DisallowStartIfOnBatteries
WakeToRun = $Task.Settings.WakeToRun
}
if($options.StartIfIdle)
{
$options += @{
IdleDuration = ConvertTo-TimeSpan $Task.Settings.IdleSettings.IdleDuration
IdleTimeout = ConvertTo-TimeSpan $Task.Settings.IdleSettings.WaitTimeout
StopIfGoingOffIdle = $Task.Settings.IdleSettings.StopOnIdleEnd
RestartOnIdleResume = $Task.Settings.IdleSettings.RestartOnIdle
}
}
$argumentList = $Argument.Trim() -split '(?<=^[^"]*(?:"[^"]*"[^"]*)*)\s+'
$params = @{
Name = $Task.TaskName
Credential = $CredentialCache[$userid]
ScheduledJobOption = New-ScheduledJobOption @options
}
[Xml.XmlElement]$triggers = Export-ScheduledTask $Task.TaskName |Select-Xml /task:Task/task:Triggers |ForEach-Object Node
if($triggers.ChildNodes.Count -eq 0){Write-Warning "Task $($Task.TaskName) has no triggers."}
else
{
$trigger = $triggers.ChildNodes |ConvertTo-JobTrigger
if($trigger) { $params += @{ Trigger = $trigger } }
}
$params +=
if($Script -is [string]) {@{ FilePath = $Script.Trim('"') }}
elseif($Script -is [ScriptBlock]) {@{ ScriptBlock = $Script }}
if($argumentList) {$params['ArgumentList']= $argumentList}
if($PSCmdlet.ShouldProcess($Task.TaskName,'disable scheduled task'))
{
Disable-ScheduledTask $Task.TaskName
}
if($PSCmdlet.ShouldProcess((ConvertTo-Json $params -Compress),'register scheduled job'))
{
Register-ScheduledJob @params
}
}
function Convert-ScheduledTask
{
[CmdletBinding()] Param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)][ciminstance]$Task
)
Begin
{
$FilePathParam = @'
(?ix) (?# case-insensitive, extended syntax )
(?:^|(?<=\s)) (?# following either the start of the string or a space )
-F(?:i(?:le?)?)? \s+ (?# -File param, or any accepted abbreviations of it )
(?<FilePath>\S+|"[^"]+") (?# the script file path: spaceless, or quoted )
(?<Params>.*) (?# followed by any parameters for the script )
'@
$CommandParam = @'
(?ix) (?# case-insensitive, extended syntax )
(?:^|(?<=\s)) (?# following either the start of the string or a space )
-C(?:o(?:m(?:m(?:a(?:nd?)?)?)?)?)? \s+ (?# -Command param, or any accepted abbreviations of it )
(?<ScriptBlock>\S+|"[^"]+"|\{[^}]*\}) (?# the script block: spaceless, quoted, or brace-delimited )
(?<Params>.*) (?# followed by any parameters for the script )
'@
}
Process
{
if($Task.Actions.Count -ne 1)
{
Write-Warning "Task '$($Task.TaskName)' has $($Task.Actions.Count) actions, skipping."
return
}
$a = $Task.Actions[0]
if((Split-Path $a.Execute -Leaf) -ne 'powershell.exe')
{
Write-Verbose "Task '$($Task.TaskName)' is not a PowerShell task."
}
elseif($a.Arguments -match $FilePathParam)
{
$workdir,$filepath = $a.WorkingDirectory,$Matches.FilePath.Trim('"')
Write-Verbose "Converting '$($Task.TaskName)' as a PowerShell file task ($filePath; $workdir)."
$file =
if([io.path]::IsPathRooted($filepath)) { $filepath }
else { Join-Path $workdir $filepath }
Convert-ScheduledTaskToJob $Task $file $Matches.Params
}
elseif($a.Arguments -match $CommandParam)
{
Write-Verbose "Converting '$($Task.TaskName)' as a PowerShell command task."
$block = [ScriptBlock]::Create(($Matches.ScriptBlock -replace '^\s*["{]|[}"]\s*$',''))
Convert-ScheduledTaskToJob $Task $block $Matches.Params
}
else
{
Write-Warning "Task '$($Task.TaskName)' is not a recognized PowerShell task: $($a.Arguments)"
}
}
}
Get-ScheduledTask -TaskPath $TaskPath |Convert-ScheduledTask