forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetJobDefinition.cs
More file actions
521 lines (466 loc) · 19.2 KB
/
Copy pathSetJobDefinition.cs
File metadata and controls
521 lines (466 loc) · 19.2 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
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
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.ScheduledJob
{
/// <summary>
/// This cmdlet updates a scheduled job definition object based on the provided
/// parameter values and saves changes to job store and Task Scheduler.
/// </summary>
[Cmdlet(VerbsCommon.Set, "ScheduledJob", DefaultParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet,
HelpUri = "http://go.microsoft.com/fwlink/?LinkID=223924")]
[OutputType(typeof(ScheduledJobDefinition))]
public sealed class SetScheduledJobCommand : ScheduleJobCmdletBase
{
#region Parameters
private const string ExecutionParameterSet = "Execution";
private const string ScriptBlockParameterSet = "ScriptBlock";
private const string FilePathParameterSet = "FilePath";
/// <summary>
/// Name of scheduled job definition.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[ValidateNotNullOrEmpty]
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _name;
/// <summary>
/// File path for script to be run in job.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[ValidateNotNullOrEmpty]
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
private string _filePath;
/// <summary>
/// ScriptBlock containing script to run in job.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[ValidateNotNull]
public ScriptBlock ScriptBlock
{
get { return _scriptBlock; }
set { _scriptBlock = value; }
}
private ScriptBlock _scriptBlock;
/// <summary>
/// Triggers to define when job will run.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public ScheduledJobTrigger[] Trigger
{
get { return _triggers; }
set { _triggers = value; }
}
private ScheduledJobTrigger[] _triggers;
/// <summary>
/// Initialization script to run before the job starts.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[ValidateNotNull]
public ScriptBlock InitializationScript
{
get { return _initializationScript; }
set { _initializationScript = value; }
}
private ScriptBlock _initializationScript;
/// <summary>
/// Runs the job in a 32-bit PowerShell process.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
public SwitchParameter RunAs32
{
get { return _runAs32; }
set { _runAs32 = value; }
}
private SwitchParameter _runAs32;
/// <summary>
/// Credentials for job.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[Credential()]
public PSCredential Credential
{
get { return _credential; }
set { _credential = value; }
}
private PSCredential _credential;
/// <summary>
/// Authentication mechanism to use for job.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
public AuthenticationMechanism Authentication
{
get { return _authenticationMechanism; }
set { _authenticationMechanism = value; }
}
private AuthenticationMechanism _authenticationMechanism;
/// <summary>
/// Scheduling options for job.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[ValidateNotNull]
public ScheduledJobOptions ScheduledJobOption
{
get { return _options; }
set { _options = value; }
}
private ScheduledJobOptions _options;
/// <summary>
/// Input for the job.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)]
[ValidateNotNull]
public ScheduledJobDefinition InputObject
{
get { return _definition; }
set { _definition = value; }
}
private ScheduledJobDefinition _definition;
/// <summary>
/// ClearExecutionHistory
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)]
public SwitchParameter ClearExecutionHistory
{
get { return _clearExecutionHistory; }
set { _clearExecutionHistory = value; }
}
private SwitchParameter _clearExecutionHistory;
/// <summary>
/// Maximum number of job results allowed in job store.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
public int MaxResultCount
{
get { return _executionHistoryLength; }
set { _executionHistoryLength = value; }
}
private int _executionHistoryLength;
/// <summary>
/// Pass the ScheduledJobDefinition object through to output.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)]
public SwitchParameter PassThru
{
get { return _passThru; }
set { _passThru = value; }
}
private SwitchParameter _passThru;
/// <summary>
/// Argument list.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public object[] ArgumentList
{
get { return _arguments; }
set { _arguments = value; }
}
private object[] _arguments;
/// <summary>
/// Runs scheduled job immediately after successfully setting job definition.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
public SwitchParameter RunNow
{
get { return _runNow; }
set { _runNow = value; }
}
private SwitchParameter _runNow;
/// <summary>
/// Runs scheduled job at the repetition interval indicated by the
/// TimeSpan value for an unending duration.
/// </summary>
[Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)]
[Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)]
public TimeSpan RunEvery
{
get { return _runEvery; }
set { _runEvery = value; }
}
private TimeSpan _runEvery;
#endregion
#region Cmdlet Overrides
/// <summary>
/// Process input.
/// </summary>
protected override void ProcessRecord()
{
switch (ParameterSetName)
{
case ExecutionParameterSet:
UpdateExecutionDefinition();
break;
case ScriptBlockParameterSet:
case FilePathParameterSet:
UpdateDefinition();
break;
}
try
{
// If RunEvery parameter is specified then create a job trigger for the definition that
// runs the job at the requested interval.
bool addedTrigger = false;
if (MyInvocation.BoundParameters.ContainsKey("RunEvery"))
{
AddRepetitionJobTriggerToDefinition(
_definition,
RunEvery,
false);
addedTrigger = true;
}
if (Trigger != null || ScheduledJobOption != null || Credential != null || addedTrigger)
{
// Save definition to file and update WTS.
_definition.Save();
}
else
{
// No WTS changes. Save definition to store only.
_definition.SaveToStore();
}
if (_runNow)
{
_definition.RunAsTask();
}
}
catch (ScheduledJobException e)
{
ErrorRecord errorRecord;
if (e.InnerException != null &&
e.InnerException is System.UnauthorizedAccessException)
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAccessOnSetJobDefinition, _definition.Name);
errorRecord = new ErrorRecord(new RuntimeException(msg, e),
"NoAccessFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition);
}
else if (e.InnerException != null &&
e.InnerException is System.IO.IOException)
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.IOFailureOnSetJobDefinition, _definition.Name);
errorRecord = new ErrorRecord(new RuntimeException(msg, e),
"IOFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition);
}
else
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSetJobDefinition, _definition.Name);
errorRecord = new ErrorRecord(new RuntimeException(msg, e),
"CantSetPropertiesToScheduledJobDefinition", ErrorCategory.InvalidOperation, _definition);
}
WriteError(errorRecord);
}
if (_passThru)
{
WriteObject(_definition);
}
}
#endregion
#region Private Methods
private void UpdateExecutionDefinition()
{
if (_clearExecutionHistory)
{
_definition.ClearExecutionHistory();
}
}
private void UpdateDefinition()
{
if (_name != null &&
string.Compare(_name, _definition.Name, StringComparison.OrdinalIgnoreCase) != 0)
{
_definition.RenameAndSave(_name);
}
UpdateJobInvocationInfo();
if (MyInvocation.BoundParameters.ContainsKey("MaxResultCount"))
{
_definition.SetExecutionHistoryLength(MaxResultCount, false);
}
if (Credential != null)
{
_definition.Credential = Credential;
}
if (Trigger != null)
{
_definition.SetTriggers(Trigger, false);
}
if (ScheduledJobOption != null)
{
_definition.UpdateOptions(ScheduledJobOption, false);
}
}
/// <summary>
/// Create new ScheduledJobInvocationInfo object with update information and
/// update the job definition object.
/// </summary>
private void UpdateJobInvocationInfo()
{
Dictionary<string, object> parameters = UpdateParameters();
string name = _definition.Name;
string command;
if (ScriptBlock != null)
{
command = ScriptBlock.ToString();
}
else if (FilePath != null)
{
command = FilePath;
}
else
{
command = _definition.InvocationInfo.Command;
}
JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), command, name);
jobDefinition.ModuleName = ModuleName;
JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameters);
_definition.UpdateJobInvocationInfo(jobInvocationInfo, false);
}
/// <summary>
/// Creates a new parameter dictionary with update parameters.
/// </summary>
/// <returns>Updated parameters.</returns>
private Dictionary<string, object> UpdateParameters()
{
Debug.Assert(_definition.InvocationInfo.Parameters.Count != 0,
"ScheduledJobDefinition must always have some job invocation parameters");
Dictionary<string, object> newParameters = new Dictionary<string, object>();
foreach (CommandParameter parameter in _definition.InvocationInfo.Parameters[0])
{
newParameters.Add(parameter.Name, parameter.Value);
}
// RunAs32
if (MyInvocation.BoundParameters.ContainsKey("RunAs32"))
{
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.RunAs32Parameter))
{
newParameters[ScheduledJobInvocationInfo.RunAs32Parameter] = RunAs32.ToBool();
}
else
{
newParameters.Add(ScheduledJobInvocationInfo.RunAs32Parameter, RunAs32.ToBool());
}
}
// Authentication
if (MyInvocation.BoundParameters.ContainsKey("Authentication"))
{
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.AuthenticationParameter))
{
newParameters[ScheduledJobInvocationInfo.AuthenticationParameter] = Authentication;
}
else
{
newParameters.Add(ScheduledJobInvocationInfo.AuthenticationParameter, Authentication);
}
}
// InitializationScript
if (InitializationScript == null)
{
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.InitializationScriptParameter))
{
newParameters.Remove(ScheduledJobInvocationInfo.InitializationScriptParameter);
}
}
else
{
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.InitializationScriptParameter))
{
newParameters[ScheduledJobInvocationInfo.InitializationScriptParameter] = InitializationScript;
}
else
{
newParameters.Add(ScheduledJobInvocationInfo.InitializationScriptParameter, InitializationScript);
}
}
// ScriptBlock
if (ScriptBlock != null)
{
// FilePath cannot also be specified.
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter))
{
newParameters.Remove(ScheduledJobInvocationInfo.FilePathParameter);
}
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter))
{
newParameters[ScheduledJobInvocationInfo.ScriptBlockParameter] = ScriptBlock;
}
else
{
newParameters.Add(ScheduledJobInvocationInfo.ScriptBlockParameter, ScriptBlock);
}
}
// FilePath
if (FilePath != null)
{
// ScriptBlock cannot also be specified.
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter))
{
newParameters.Remove(ScheduledJobInvocationInfo.ScriptBlockParameter);
}
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter))
{
newParameters[ScheduledJobInvocationInfo.FilePathParameter] = FilePath;
}
else
{
newParameters.Add(ScheduledJobInvocationInfo.FilePathParameter, FilePath);
}
}
// ArgumentList
if (ArgumentList == null)
{
// Clear existing argument list only if new scriptblock or script file path was specified
// (in this case old argument list is invalid).
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter) &&
(ScriptBlock != null || FilePath != null))
{
newParameters.Remove(ScheduledJobInvocationInfo.ArgumentListParameter);
}
}
else
{
if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter))
{
newParameters[ScheduledJobInvocationInfo.ArgumentListParameter] = ArgumentList;
}
else
{
newParameters.Add(ScheduledJobInvocationInfo.ArgumentListParameter, ArgumentList);
}
}
return newParameters;
}
#endregion
}
}