-
-
Notifications
You must be signed in to change notification settings - Fork 272
/
Get-ScheduledTasks.ps1
321 lines (270 loc) · 13.8 KB
/
Get-ScheduledTasks.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
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
function Get-ScheduledTasks {
<#
.SYNOPSIS
Get scheduled task information from a system
.DESCRIPTION
Get scheduled task information from a system
Uses Schedule.Service COM object, falls back to SchTasks.exe as needed.
When we fall back to SchTasks, we add empty properties to match the COM object output.
.PARAMETER ComputerName
One or more computers to run this against
.PARAMETER Folder
Scheduled tasks folder to query. By default, "\"
.PARAMETER Recurse
If specified, recurse through folders below $folder.
Note: We also recurse if we use SchTasks.exe
.PARAMETER Path
If specified, path to export XML files
Details:
Naming scheme is computername-taskname.xml
Please note that the base filename is used when importing a scheduled task. Rename these as needed prior to importing!
.PARAMETER Exclude
If specified, exclude tasks matching this regex (we use -notmatch $exclude)
.PARAMETER CompatibilityMode
If specified, pull scheduled tasks only with the schtasks.exe command, which works against older systems.
Notes:
Export is not possible with this switch.
Recurse is implied with this switch.
.EXAMPLE
#Get scheduled tasks from the root folder of server1 and c-is-ts-91
Get-ScheduledTasks server1, c-is-ts-91
.EXAMPLE
#Get scheduled tasks from all folders on server1, not in a Microsoft folder
Get-ScheduledTasks server1 -recurse -Exclude "\\Microsoft\\"
.EXAMPLE
#Get scheduled tasks from all folders on server1, not in a Microsoft folder, and export in XML format (can be used to import scheduled tasks)
Get-ScheduledTasks server1 -recurse -Exclude "\\Microsoft\\" -path 'D:\Scheduled Tasks'
.NOTES
Properties returned : When they will show up
ComputerName : All queries
Name : All queries
Path : COM object queries, added synthetically if we fail back from COM to SchTasks
Enabled : COM object queries
Action : All queries. Schtasks.exe queries include both Action and Arguments in this property
Arguments : COM object queries
UserId : COM object queries
LastRunTime : All queries
NextRunTime : All queries
Status : All queries
Author : All queries
RunLevel : COM object queries
Description : COM object queries
NumberOfMissedRuns : COM object queries
Thanks to help from Brian Wilhite, Jaap Brasser, and Jan Egil's functions:
http://gallery.technet.microsoft.com/scriptcenter/Get-SchedTasks-Determine-5e04513f
http://gallery.technet.microsoft.com/scriptcenter/Get-Scheduled-tasks-from-3a377294
http://blog.crayon.no/blogs/janegil/archive/2012/05/28/working_2D00_with_2D00_scheduled_2D00_tasks_2D00_from_2D00_windows_2D00_powershell.aspx
.FUNCTIONALITY
Computers
#>
[cmdletbinding(
DefaultParameterSetName='COM'
)]
param(
[parameter(
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
Position=0
)]
[Alias("host","server","computer")]
[string[]]$ComputerName = "localhost",
[parameter()]
[string]$folder = "\",
[parameter(ParameterSetName='COM')]
[switch]$recurse,
[parameter(ParameterSetName='COM')]
[validatescript({
#Test path if provided, otherwise allow $null
if($_){
Test-Path -PathType Container -path $_
}
else {
$true
}
})]
[string]$Path = $null,
[parameter()]
[string]$Exclude = $null,
[parameter(ParameterSetName='SchTasks')]
[switch]$CompatibilityMode
)
Begin{
if(-not $CompatibilityMode){
$sch = New-Object -ComObject Schedule.Service
#thanks to Jaap Brasser - http://gallery.technet.microsoft.com/scriptcenter/Get-Scheduled-tasks-from-3a377294
function Get-AllTaskSubFolders {
[cmdletbinding()]
param (
# Set to use $Schedule as default parameter so it automatically list all files
# For current schedule object if it exists.
$FolderRef = $sch.getfolder("\"),
[switch]$recurse
)
#No recurse? Return the folder reference
if (-not $recurse) {
$FolderRef
}
#Recurse? Build up an array!
else {
Try{
#This will fail on older systems...
$folders = $folderRef.getfolders(1)
#Extract results into array
$ArrFolders = @(
if($folders) {
foreach ($fold in $folders) {
$fold
if($fold.getfolders(1)) {
Get-AllTaskSubFolders -FolderRef $fold
}
}
}
)
}
Catch{
#If we failed and the expected error, return folder ref only!
if($_.tostring() -like '*Exception calling "GetFolders" with "1" argument(s): "The request is not supported.*')
{
$folders = $null
Write-Warning "GetFolders failed, returning root folder only: $_"
Return $FolderRef
}
else{
Throw $_
}
}
#Return only unique results
$Results = @($ArrFolders) + @($FolderRef)
$UniquePaths = $Results | select -ExpandProperty path -Unique
$Results | ?{$UniquePaths -contains $_.path}
}
} #Get-AllTaskSubFolders
}
function Get-SchTasks {
[cmdletbinding()]
param([string]$computername, [string]$folder, [switch]$CompatibilityMode)
#we format the properties to match those returned from com objects
$result = @( schtasks.exe /query /v /s $computername /fo csv |
convertfrom-csv |
?{$_.taskname -ne "taskname" -and $_.taskname -match $( $folder.replace("\","\\") ) } |
select @{ label = "ComputerName"; expression = { $computername } },
@{ label = "Name"; expression = { $_.TaskName } },
@{ label = "Action"; expression = {$_."Task To Run"} },
@{ label = "LastRunTime"; expression = {$_."Last Run Time"} },
@{ label = "NextRunTime"; expression = {$_."Next Run Time"} },
"Status",
"Author"
)
if($CompatibilityMode){
#User requested compat mode, don't add props
$result
}
else{
#If this was a failback, we don't want to affect display of props for comps that don't fail... include empty props expected for com object
#We also extract task name and path to parent for the Name and Path props, respectively
foreach($item in $result){
$name = @( $item.Name -split "\\" )[-1]
$taskPath = $item.name
$item | select ComputerName, @{ label = "Name"; expression = {$name}}, @{ label = "Path"; Expression = {$taskPath}}, Enabled, Action, Arguments, UserId, LastRunTime, NextRunTime, Status, Author, RunLevel, Description, NumberOfMissedRuns
}
}
} #Get-SchTasks
}
Process{
#loop through computers
foreach($computer in $computername){
#bool in case com object fails, fall back to schtasks
$failed = $false
write-verbose "Running against $computer"
Try {
#use com object unless in compatibility mode. Set compatibility mode if this fails
if(-not $compatibilityMode){
Try{
#Connect to the computer
$sch.Connect($computer)
if($recurse)
{
$AllFolders = Get-AllTaskSubFolders -FolderRef $sch.GetFolder($folder) -recurse -ErrorAction stop
}
else
{
$AllFolders = Get-AllTaskSubFolders -FolderRef $sch.GetFolder($folder) -ErrorAction stop
}
Write-verbose "Looking through $($AllFolders.count) folders on $computer"
foreach($fold in $AllFolders){
#Get tasks in this folder
$tasks = $fold.GetTasks(0)
Write-Verbose "Pulling data from $($tasks.count) tasks on $computer in $($fold.name)"
foreach($task in $tasks){
#extract helpful items from XML
$Author = ([regex]::split($task.xml,'<Author>|</Author>'))[1]
$UserId = ([regex]::split($task.xml,'<UserId>|</UserId>'))[1]
$Description =([regex]::split($task.xml,'<Description>|</Description>'))[1]
$Action = ([regex]::split($task.xml,'<Command>|</Command>'))[1]
$Arguments = ([regex]::split($task.xml,'<Arguments>|</Arguments>'))[1]
$RunLevel = ([regex]::split($task.xml,'<RunLevel>|</RunLevel>'))[1]
$LogonType = ([regex]::split($task.xml,'<LogonType>|</LogonType>'))[1]
#convert state to status
Switch ($task.State) {
0 {$Status = "Unknown"}
1 {$Status = "Disabled"}
2 {$Status = "Queued"}
3 {$Status = "Ready"}
4 {$Status = "Running"}
}
#output the task details
if(-not $exclude -or $task.Path -notmatch $Exclude){
$task | select @{ label = "ComputerName"; expression = { $computer } },
Name,
Path,
Enabled,
@{ label = "Action"; expression = {$Action} },
@{ label = "Arguments"; expression = {$Arguments} },
@{ label = "UserId"; expression = {$UserId} },
LastRunTime,
NextRunTime,
@{ label = "Status"; expression = {$Status} },
@{ label = "Author"; expression = {$Author} },
@{ label = "RunLevel"; expression = {$RunLevel} },
@{ label = "Description"; expression = {$Description} },
NumberOfMissedRuns
#if specified, output the results in importable XML format
if($path){
$xml = $task.Xml
$taskname = $task.Name
$xml | Out-File $( Join-Path $path "$computer-$taskname.xml" )
}
}
}
}
}
Catch{
Write-Warning "Could not pull scheduled tasks from $computer using COM object, falling back to schtasks.exe"
Try{
Get-SchTasks -computername $computer -folder $folder -ErrorAction stop
}
Catch{
Write-Error "Could not pull scheduled tasks from $computer using schtasks.exe:`n$_"
Continue
}
}
}
#otherwise, use schtasks
else{
Try{
Get-SchTasks -computername $computer -folder $folder -CompatibilityMode -ErrorAction stop
}
Catch{
Write-Error "Could not pull scheduled tasks from $computer using schtasks.exe:`n$_"
Continue
}
}
}
Catch{
Write-Error "Error pulling Scheduled tasks from $computer`: $_"
Continue
}
}
}
}