-
Notifications
You must be signed in to change notification settings - Fork 0
/
JobScheduler.psm1
2693 lines (2206 loc) · 106 KB
/
JobScheduler.psm1
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
JobScheduler command line interface
For further information see
PS > about_JobScheduler
If the documentation is not available for your language then consider to use
PS > [System.Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'
#>
# --------------------------------
# Globals with JobScheduler Master
# --------------------------------
# JobScheduler Master Object
[PSObject] $script:js = $null
# CLI operated for a JobScheduler job or monitor
[bool] $script:jsOperations = ( $spooler -and $spooler.id() )
# JobScheduler Master environment
[hashtable] $script:jsEnv = @{}
# Commands that require a local Master instance (Management of Windows Service)
[string[]] $script:jsLocalCommands = @( 'Install-JobSchedulerService', 'Remove-JobSchedulerService', 'Start-JobSchedulerMaster' )
# -------------------------------
# Globals with JobScheduler Agent
# -------------------------------
# JobScheduler Agent Object
[PSObject] $script:jsAgent = $null
# Commands that require a local Agent instance (Management of Windows Service)
[string[]] $script:jsAgentLocalCommands = @( 'Install-JobSchedulerAgentService', 'Remove-JobSchedulerAgentService', 'Start-JobSchedulerAgent' )
# -------------------------------------
# Globals with JobScheduler Web Service
# -------------------------------------
# JobScheduler Web Service Object
[PSObject] $script:jsWebService = $null
# JobScheduler Web Service Request
# Credentials
[System.Management.Automation.PSCredential] $script:jsWebServiceCredential = $null
# Use default credentials of the current user?
[bool] $script:jsWebServiceOptionWebRequestUseDefaultCredentials = $false
# Proxy Credentials
[System.Management.Automation.PSCredential] $script:jsWebServiceProxyCredential = $null
# Use default credentials of the current user?
[bool] $script:jsWebServiceOptionWebRequestProxyUseDefaultCredentials = $true
# --------------------
# Globals with Options
# --------------------
# Options
# Debug Message: responses exceeding the max. output size are stored in temporary files
[int] $script:jsOptionDebugMaxOutputSize = 1000
# Master Web Request: timeout for establishing the connection in ms
[int] $script:jsOptionWebRequestTimeout = 30
# ----------------------------------------------------------------------
# Public Functions
# ----------------------------------------------------------------------
$moduleRoot = Split-Path -Path $MyInvocation.MyCommand.Path
"$moduleRoot\functions\*.ps1" | Resolve-Path | ForEach-Object { . $_.ProviderPath }
Export-ModuleMember -Function "*"
# ----------------------------------------------------------------------
# Public Function Alias Management
# ----------------------------------------------------------------------
function Use-JobSchedulerAlias
{
<#
.SYNOPSIS
This cmdlet creates alias names for JobScheduler cmdlets.
.DESCRIPTION
To create alias names this cmdlet has to be dot sourced, i.e. use
* . Use-JobSchedulerAlias -Prefix JS: works as expected
* Use-JobSchedulerAlias-Prefix JS: has no effect
When using a number of modules from different vendors then naming conflicts might occur
for cmdlets with the same name from different modules.
The JobScheduler CLI makes use of the following policy:
* All cmdlets use a unique qualifier for the module as e.g. Use-JobSchedulerMaster, Get-JobSchedulerInventory etc.
* Users can use this cmdlet to create a shorthand notation for cmdlet alias names. Two flavors are offered:
** use a shorthand notation as e.g. Use-JSMaster instead of Use-JobSchedulerMaster. This notation is recommended as is suggests fairly unique names.
** use a shorthand notation as e.g. Use-Master instead of Use-JobSchedulerMaster. This notation can conflict with cmdlets of the PowerShell Core, e.g. for Start-Job, Stop-Job
* Users can exclude shorthand notation for specific cmdlets by use of an exclusion list.
You can find the resulting aliases by use of the command Get-Command -Module JobScheduler.
.PARAMETER Prefix
Specifies the prefix that is used for a shorthand notation, e.g.
* with the parameter -Prefix "JS" used this cmdlet creates an alias Use-JSMaster for Use-JobSchedulerMaster
* with the parameter -Prefix being omitted this cmdlet creates an alias Use-Master for Use-JobSchedulerMaster
By default aliases are created for both the prefix "JS" and with an empty prefix being assigned which results in the following possible notation:
* Use-JobSchedulerMaster
* Use-JSMaster
* Use-Master
Default: . UseJobSchedulerAlias -Prefix JS
Default: . UseJobSchedulerAlias -NoDuplicates -ExcludesPrefix JS
.PARAMETER Excludes
Specifies a list of resulting alias names that are excluded from alias creation.
When omitting the -Prefix parameter then
- at the time of writing - the following alias names would conflict with cmdlet names from the PowerShell Core:
* Get-Event
* Get-Job
* Start-Job
* Stop-Job
.PARAMETER ExcludesPrefix
Specifies a prefix that is used should a resulting alias be a member of the list of
excluded aliases that is specified with the -Excludes parameter.
When used with the -NoDuplicates parameter then this parameter specifies the prefix that is used
for aliases that would conflict with any exsting cmdlets, functions or aliases.
.PARAMETER NoDuplicates
This parameters specifies that no alias names should be created that conflict with existing cmdlets, functions or aliases.
.EXAMPLE
. Use-JobSchedulerAlias -Prefix JS
Creates aliases for all JobScheduler CLI cmdlets that allow to use, e.g. Use-JSMaster for Use-JobSchedulerMaster
.EXAMPLE
. Use-JobSchedulerAlias -Exclude Get-Job,Start-Job,Stop-Job -ExcludePrefix JS
Creates aliases for all JobScheduler CLI cmdlets that allow to use, e.g. Use-Master for Use-JobSchedulerMaster.
This is specified by omitting the -Prefix parameter.
For the resulting alias names Get-Job, Start-Job and Stop-Job the alias names
Get-JSJob, Start-JSJob and Stop-JSJob are created by use of the -ExcludePrefix "JS" parameter.
.EXAMPLE
. Use-JobSchedulerAlias -NoDuplicates -ExcludesPrefix JS
Creates aliases for all JobScheduler CLI cmdlets that allow to use e.g. Use-Master for Use-JobSchedulerMaster.
Should any alias name conflict with an existing cmdlet, function or alias then the alias will be created with the
prefix specified by the -ExcludesPrefix parameter.
The JobScheduler CLI module uses this alias setting by defalt.
.LINK
about_jobscheduler
#>
[cmdletbinding()]
param
(
[Parameter(Mandatory=$False,ValueFromPipeline=$False,ValueFromPipelinebyPropertyName=$True)]
[string] $Prefix,
[Parameter(Mandatory=$False,ValueFromPipeline=$False,ValueFromPipelinebyPropertyName=$True)]
[string[]] $Excludes,
[Parameter(Mandatory=$False,ValueFromPipeline=$False,ValueFromPipelinebyPropertyName=$True)]
[string] $ExcludesPrefix,
[Parameter(Mandatory=$False,ValueFromPipeline=$False,ValueFromPipelinebyPropertyName=$True)]
[switch] $NoDuplicates
)
Process
{
if ( $NoDuplicates )
{
$allCommands = Get-Command | Select-Object -Property Name | ForEach-Object { $_.Name }
}
$commands = Get-Command -Module JobScheduler -CommandType 'Function'
foreach( $command in $commands )
{
$aliasName = $command.name.Replace( '-JobScheduler', "-$($Prefix)" )
if ( $Excludes -contains $aliasName )
{
continue
}
if ( $Excludes -contains $aliasName )
{
if ( $ExcludesPrefix )
{
$aliasName = $command.name.Replace( '-JobScheduler', "-$($ExcludesPrefix)" )
} else {
continue
}
}
if ( $NoDuplicates )
{
if ( $allCommands -contains $aliasName )
{
if ( $ExcludesPrefix )
{
$aliasName = $command.name.Replace( '-JobScheduler', "-$($ExcludesPrefix)" )
} else {
continue
}
}
}
Set-Alias -Name $aliasName -Value $command.Name
switch( $aliasName )
{
'Start-JobEditor' {
Set-Alias -Name "Start-$($Prefix)JOE" -Value $command.Name
break;
}
'Start-Dashboard' {
Set-Alias -Name "Start-$($Prefix)JID" -Value $command.Name
break;
}
}
}
Set-Alias -Name Use-JobSchedulerWebService -Value Connect-JobScheduler
Set-Alias -Name Use-JSWebService -Value Connect-JobScheduler
Set-Alias -Name Stop-JobSchedulerJob -Value Stop-JobSchedulerTask
Set-Alias -Name Stop-JSJob -Value Stop-JobSchedulerTask
Export-ModuleMember -Alias "*"
}
}
# create alias names to shorten 'JobScheduler' to 'JS'
. Use-JobSchedulerAlias -Prefix JS -Excludes 'Connect-','Disconnect-','Use-JSAlias','Use-Alias'
# create alias names that drop 'JobScheduler' in the name but avoid conflicts with existing alias names
. Use-JobSchedulerAlias -NoDuplicates -ExcludesPrefix JS -Excludes 'Connect-','Disconnect-','Use-JSAlias','Use-Alias'
# ----------------------------------------------------------------------
# Private Functions
# ----------------------------------------------------------------------
function Approve-JobSchedulerCommand( [System.Management.Automation.CommandInfo] $command )
{
if ( !$jsWebServiceCredential )
{
throw "$($command.Name): no valid session, login to the JobScheduler Web Service with the Connect-JobScheduler cmdlet"
}
if ( !$SCRIPT:js.Local )
{
if ( $SCRIPT:jsLocalCommands -contains $command.Name )
{
throw "$($command.Name): cmdlet is available exclusively for local JobScheduler Master. Switch instance with the Use-JobSchedulerMaster cmdlet and specify the -Id or -InstallPath parameter for a local JobScheduler Master"
}
}
if ( !$SCRIPT:js.Url -and !$SCRIPT:jsOperations -and !$SCRIPT:jsWebService.JobSchedulerId )
{
if ( $SCRIPT:jsLocalCommands -notcontains $command.Name )
{
throw "$($command.Name): cmdlet requires a JobScheduler URL. Switch instance with the Connect-JobScheduler cmdlet and specify the -Url parameter"
}
}
}
function Approve-JobSchedulerAgentCommand( [System.Management.Automation.CommandInfo] $command )
{
if ( !$SCRIPT:jsAgent.Local )
{
if ( $SCRIPT:jsAgentLocalCommands -contains $command.Name )
{
throw "$($command.Name): cmdlet is available exclusively for local JobScheduler Agent. Switch instance with the Use-JobSchedulerAgent cmdlet and specify the -InstallPath parameter for a local JobScheduler Agent"
}
}
if ( !$SCRIPT:jsAgent.Url -and !$SCRIPT:jsOperations )
{
if ( $SCRIPT:jsAgentLocalCommands -notcontains $command.Name )
{
throw "$($command.Name): cmdlet requires a JobScheduler Agent URL. Switch instance with the Use-JobSchedulerAgent cmdlet and specify the -Url parameter"
}
}
}
function Start-JobSchedulerStopWatch
{
[cmdletbinding(SupportsShouldProcess)]
[OutputType([System.Diagnostics.Stopwatch])]
param
()
if ( $PSCmdlet.ShouldProcess( 'Stopwatch' ) )
{
[System.Diagnostics.Stopwatch]::StartNew()
}
}
function Trace-JobSchedulerStopWatch( [string] $CommandName, [System.Diagnostics.Stopwatch] $StopWatch )
{
if ( $StopWatch )
{
Write-Verbose ".. $($CommandName): time elapsed: $($StopWatch.Elapsed.TotalMilliseconds) ms"
}
}
function New-JobSchedulerObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'JS' ) )
{
$js = New-Object PSObject
$jsInstall = New-Object PSObject
$jsConfig = New-Object PSObject
$jsService = New-Object PSObject
$js | Add-Member -Membertype NoteProperty -Name Id -Value ''
$js | Add-Member -Membertype NoteProperty -Name Url -Value ''
$js | Add-Member -Membertype NoteProperty -Name ProxyUrl -Value ''
$js | Add-Member -Membertype NoteProperty -Name Local -Value $false
$jsInstall | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$jsInstall | Add-Member -Membertype NoteProperty -Name ExecutableFile -Value ''
$jsInstall | Add-Member -Membertype NoteProperty -Name Params -Value ''
$jsInstall | Add-Member -Membertype NoteProperty -Name StartParams -Value ''
$jsInstall | Add-Member -Membertype NoteProperty -Name ClusterOptions -Value ''
$jsInstall | Add-Member -Membertype NoteProperty -Name PidFile -Value ''
$jsConfig | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$jsConfig | Add-Member -Membertype NoteProperty -Name FactoryIni -Value ''
$jsConfig | Add-Member -Membertype NoteProperty -Name SosIni -Value ''
$jsConfig | Add-Member -Membertype NoteProperty -Name SchedulerXml -Value ''
$jsService | Add-Member -Membertype NoteProperty -Name ServiceName -Value ''
$jsService | Add-Member -Membertype NoteProperty -Name ServiceDisplayName -Value ''
$jsService | Add-Member -Membertype NoteProperty -Name ServiceDescription -Value ''
$js | Add-Member -Membertype NoteProperty -Name Install -Value $jsInstall
$js | Add-Member -Membertype NoteProperty -Name Config -Value $jsConfig
$js | Add-Member -Membertype NoteProperty -Name Service -Value $jsService
$js
}
}
function New-JobSchedulerStatisticsObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'Statistics' ) )
{
$stat = New-Object PSObject
$stat | Add-Member -Membertype NoteProperty -Name JobsExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name JobsPending -Value 0
$stat | Add-Member -Membertype NoteProperty -Name JobsRunning -Value 0
$stat | Add-Member -Membertype NoteProperty -Name JobsStopped -Value 0
$stat | Add-Member -Membertype NoteProperty -Name JobsNeedProcess -Value 0
$stat | Add-Member -Membertype NoteProperty -Name TasksExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name TasksRunning -Value 0
$stat | Add-Member -Membertype NoteProperty -Name TasksStarting -Value 0
$stat | Add-Member -Membertype NoteProperty -Name OrdersExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name OrdersClustered -Value 0
$stat | Add-Member -Membertype NoteProperty -Name OrdersStanding -Value 0
$stat | Add-Member -Membertype NoteProperty -Name SchedulesExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name ProcessClassesExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name FoldersExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name LocksExist -Value 0
$stat | Add-Member -Membertype NoteProperty -Name MonitorsExist -Value 0
$stat
}
}
function New-JobSchedulerJobChainObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'JobChain' ) )
{
$jobChain = New-Object PSObject
$jobChain | Add-Member -Membertype NoteProperty -Name JobChain -Value ''
$jobChain | Add-Member -Membertype NoteProperty -Name Path -Value ''
$jobChain | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$jobChain | Add-Member -Membertype NoteProperty -Name Volatile -Value ''
$jobChain | Add-Member -Membertype NoteProperty -Name Permanent -Value ''
$jobChain
}
}
function New-JobSchedulerOrderObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'Order' ) )
{
$order = New-Object PSObject
$order | Add-Member -Membertype NoteProperty -Name OrderId -Value ''
$order | Add-Member -Membertype NoteProperty -Name JobChain -Value ''
$order | Add-Member -Membertype NoteProperty -Name Path -Value ''
$order | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$order | Add-Member -Membertype NoteProperty -Name Volatile -Value ''
$order | Add-Member -Membertype NoteProperty -Name Permanent -Value ''
$order | Add-Member -Membertype NoteProperty -Name OrderHistory -Value @()
$order
}
}
function New-JobSchedulerJobObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'Job' ) )
{
$job = New-Object PSObject
$job | Add-Member -Membertype NoteProperty -Name Job -Value ''
$job | Add-Member -Membertype NoteProperty -Name Path -Value ''
$job | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$job | Add-Member -Membertype NoteProperty -Name Volatile -Value ''
$job | Add-Member -Membertype NoteProperty -Name Permanent -Value ''
$job | Add-Member -Membertype NoteProperty -Name Tasks -Value @()
$job | Add-Member -Membertype NoteProperty -Name TaskHistory -Value @()
$job
}
}
function New-JobSchedulerEventObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'Event' ) )
{
$jsEvent = New-Object PSObject
$jsEvent | Add-Member -Membertype NoteProperty -Name EventClass -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name EventId -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name ExitCode -Value 0
$jsEvent | Add-Member -Membertype NoteProperty -Name Job -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name JobChain -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name Order -Value ''
# $jsEvent | Add-Member -Membertype NoteProperty -Name MasterUrl -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name ExpirationDate -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name ExpirationCycle -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name ExpirationPeriod -Value ''
$jsEvent | Add-Member -Membertype NoteProperty -Name Created -Value ''
$jsEvent
}
}
function New-JobSchedulerAgenObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'Agent' ) )
{
$jsAgent = New-Object PSObject
$jsAgentInstall = New-Object PSObject
$jsAgentConfig = New-Object PSObject
$jsAgentService = New-Object PSObject
$jsAgent | Add-Member -Membertype NoteProperty -Name Url -Value ''
$jsAgent | Add-Member -Membertype NoteProperty -Name ProxyUrl -Value ''
$jsAgent | Add-Member -Membertype NoteProperty -Name Local -Value $false
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name ExecutableFile -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name Params -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name StartParams -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name HttpPort -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name HttpsPort -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name LogDirectory -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name PidFileDirectory -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name WorkingDirectory -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name KillScript -Value ''
$jsAgentInstall | Add-Member -Membertype NoteProperty -Name InstanceScript -Value ''
$jsAgentConfig | Add-Member -Membertype NoteProperty -Name Directory -Value ''
$jsAgentService | Add-Member -Membertype NoteProperty -Name ServiceName -Value ''
$jsAgentService | Add-Member -Membertype NoteProperty -Name ServiceDisplayName -Value ''
$jsAgentService | Add-Member -Membertype NoteProperty -Name ServiceDescription -Value ''
$jsAgent | Add-Member -Membertype NoteProperty -Name Install -Value $jsAgentInstall
$jsAgent | Add-Member -Membertype NoteProperty -Name Config -Value $jsAgentConfig
$jsAgent | Add-Member -Membertype NoteProperty -Name Service -Value $jsAgentService
$jsAgent
}
}
function New-JobSchedulerWebServiceObject
{
[cmdletbinding(SupportsShouldProcess)]
param
()
if ( $PSCmdlet.ShouldProcess( 'WebService' ) )
{
$jsWebService = New-Object PSObject
$jsWebService | Add-Member -Membertype NoteProperty -Name Url -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name ProxyUrl -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name Base -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name Timeout -Value $script:jsOptionWebRequestTimeout
$jsWebService | Add-Member -Membertype NoteProperty -Name SkipCertificateCheck -Value $false
$jsWebService | Add-Member -Membertype NoteProperty -Name SSLProtocol -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name Certificate -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name JobSchedulerId -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name AccessToken -Value ''
$jsWebService | Add-Member -Membertype NoteProperty -Name Masters -Value @()
$jsWebService
}
}
function isPowerShellVersion( [int] $Major=-1, [int] $Minor=-1, [int] $Patch=-1 )
{
$rc = $false
if ( $Major -gt -1 )
{
if ( $PSVersionTable.PSVersion.Major -eq $Major )
{
if ( $Minor -gt -1 )
{
if ( $PSVersionTable.PSVersion.Minor -eq $Minor )
{
if ( $Patch -gt - 1 )
{
if ( $PSVersionTable.PSVersion.Patch -ge $Patch )
{
$rc = $true
}
} else {
$rc = $true
}
} elseif ( $PSVersionTable.PSVersion.Minor -gt $Minor ) {
$rc = $true
} else {
$rc = $true
}
} else {
$rc = $true
}
} elseif ( $PSVersionTable.PSVersion.Major -gt $Major ) {
$rc = $true
}
}
$rc
}
function Invoke-JobSchedulerWebRequest( [string] $Path, [string] $Body, [string] $ContentType='application/json', [hashtable] $Headers=@{'Accept' = 'application/json'}, [Uri] $Url, [string] $Method='POST' )
{
if ( $Url )
{
$requestUrl = $Url.OriginalString + $Path
} elseif ( $script:jsWebService.Url.UserInfo )
{
$requestUrl = $script:jsWebService.Url.scheme + '://' + $script:jsWebService.Url.UserInfo + '@' + $script:jsWebService.Url.Authority + $script:jsWebService.Base + $Path
} else {
$requestUrl = $script:jsWebService.Url.scheme + '://' + $script:jsWebService.Url.Authority + $script:jsWebService.Base + $Path
}
$requestParams = @{}
$requestParams.Add( 'Verbose', $false )
$requestParams.Add( 'Uri', $requestUrl )
$requestParams.Add( 'Method', $Method )
$requestParams.Add( 'ContentType', $ContentType )
$Headers.Add( 'Content-Type', $ContentType )
$Headers.Add( 'X-Access-Token', $script:jsWebService.AccessToken )
$requestParams.Add( 'Headers', $Headers )
if ( isPowerShellVersion 6 )
{
$requestParams.Add( 'AllowUnencryptedAuthentication', $true )
}
if ( isPowerShellVersion 7 )
{
$requestParams.Add( 'SkipHttpErrorCheck', $true )
}
if ( $script:jsWebService.Timeout )
{
$requestParams.Add( 'TimeoutSec', $script:jsWebService.Timeout )
}
if ( $script:jsWebService.SkipCertificateCheck )
{
$requestParams.Add( 'SkipCertificateCheck', $true )
}
if ( $script:jsWebService.SSLProtocol )
{
$requestParams.Add( 'SSLProtocol', $script:jsWebService.SSLProtocol )
}
if ( $script:jsWebService.Certificate )
{
$requestParams.Add( 'Certificate', $script:jsWebService.Certificate )
}
if ( $Body )
{
$requestParams.Add( 'Body', $Body )
}
try
{
Write-Debug ".. $($MyInvocation.MyCommand.Name): sending request to JobScheduler Web Service $($requestUrl)"
Write-Debug ".... Invoke-WebRequest:"
$requestParams.Keys | ForEach-Object {
if ( $_ -eq 'Headers' )
{
$item = $_
$requestParams.Item($_).Keys | ForEach-Object {
Write-Debug "...... Header: $_ : $($requestParams.Item($item).Item($_))"
}
} else {
if ( $_ -ne 'Certificate' )
{
Write-Debug "...... Argument: $_ $($requestParams.Item($_))"
}
}
}
if ( isPowerShellVersion 7 )
{
$response = Invoke-WebRequest @requestParams
} else {
try
{
$response = Invoke-WebRequest @requestParams
} catch {
$response = $_.Exception.Response
}
}
if ( $response -and $response.StatusCode -and $response.Content )
{
$response
} elseif ( $response -and !(isPowerShellVersion 7) ) {
$response
} else {
$message = $response | Format-List -Force | Out-String
throw $message
}
} catch {
$message = $_.Exception | Format-List -Force | Out-String
throw $message
}
}
function Invoke-JobSchedulerWebRequestXmlCommand( [string] $Command, [switch] $IgnoreResponse, [string] $Path='/jobscheduler/commands', [Uri] $Uri, $Method='POST', $ContentType='application/xml', [hashtable] $Headers=@{'Accept' = 'application/xml'} )
{
$xmlDoc = [xml] $command
if ($xmlDoc.commands)
{
$command = $xmlDoc.commands.innerXml
}
# handle XML and JSON requests
if ( $Command.startsWith( '<' ) )
{
if ( $Command -notcontains '<jobscheduler_commands' )
{
$Command = "<jobscheduler_commands jobschedulerId='$($script:jsWebService.JobSchedulerId)'>$($Command)</jobscheduler_commands>"
}
$ContentType = 'application/xml'
}
if ( $Uri )
{
$response = Invoke-JobSchedulerWebRequest -Uri $Uri -Method $Methhod -Body $Command -ContentType $ContentType -Headers $Headers
} else {
$response = Invoke-JobSchedulerWebRequest -Path $Path -Method $Methhod -Body $Command -ContentType $ContentType -Headers $Headers
}
if ( $response.StatusCode -ne 200 )
{
throw ( $response | Format-List -Force | Out-String )
}
if ( $IgnoreResponse )
{
return $response
}
if ( $response.Headers.'Content-Type' -eq 'application/xml' )
{
try
{
$answer = Select-XML -Content $response.Content -Xpath '/spooler/answer'
if ( !$answer )
{
throw 'missing answer element /spooler/answer in response'
}
} catch {
throw 'not a valid JobScheduler XML response: ' + $_.Exception.Message
}
$errorText = Select-XML -Content $response.Content -Xpath '/spooler/answer/ERROR/@text'
if ( $errorText.Node."#text" )
{
throw $errorText.Node."#text"
}
try
{
[xml] $response.Content
} catch {
throw ( $_.Exception | Format-List -Force | Out-String )
}
} else {
throw "Web Service response received with unsupported content type: $($response.Headers.'Content-Type')"
}
}
# return the directory name of a path
function Get-DirectoryName( [string] $path )
{
if ( $path.LastIndexOf('\') -ge 0 )
{
$path = $path.Substring( $path.LastIndexOf('\')+1 )
} elseif ( $path.LastIndexOf('/') -ge 0 ) {
$path = $path.Substring( $path.LastIndexOf('/')+1 )
}
$path
}
# return the basename of an object
function Get-JobSchedulerObject-Basename( [string] $objectPath )
{
if ( $objectPath.LastIndexOf('/') -ge 0 )
{
$objectPath = $objectPath.Substring( $objectPath.LastIndexOf('/')+1 )
}
$objectPath
}
# return the parent folder of an object
function Get-JobSchedulerObject-Parent( [string] $objectPath )
{
if ( $objectPath.LastIndexOf('/') -ge 0 )
{
$objectPath.Substring( 0, $objectPath.LastIndexOf('/') )
}
}
# return the canonical path of an object, i.e. the full path
function Get-JobSchedulerObject-CanonicalPath( [string] $objectPath )
{
if ( $objectPath.LastIndexOf('/') -ge 0 )
{
$objectPath = $objectPath.Substring( 0, $objectPath.LastIndexOf('/') )
}
$objectPath = ([string] $spooler.configuration_directory()) + $objectPath
$objectPath
}
# execute Windows command script and return environment variables
function Invoke-CommandScript
{
<#
.SYNOPSIS
Invoke the specified batch file (and parameters), but also propagate any
environment variable changes back to the PowerShell environment that
called it.
#>
param
(
[Parameter(Mandatory = $true)]
[string] $Path,
[string] $ArgumentList
)
#Set-StrictMode -Version 3
$tempFile = [IO.Path]::GetTempFileName()
## Store the output of cmd.exe. We also ask cmd.exe to output
## the environment table after the batch file completes
## cmd /c " `"$Path`" $ArgumentList && set > `"$tempFile`" "
$process = Start-Process -FilePath "cmd.exe" "/c ""`"$Path`" $ArgumentList && set > `"$tempFile`""" " -WindowStyle Hidden -PassThru -Wait
if ( !$process.ExitCode -eq 0 )
{
throw "$($MyInvocation.MyCommand.Name): command script execution failed with exit code: $($process.ExitCode)"
}
## Go through the environment variables in the temp file.
## For each of them, set the variable in our local environment.
Get-Content $tempFile | Foreach-Object {
if($_ -match "^(.*?)=(.*)$")
{
# Set-Content "env:\$($matches[1])" $matches[2]
$script:jsEnv["$($matches[1])"] = $matches[2]
}
}
Remove-Item $tempFile
}
function New-JobSchedulerParamNode
{
[cmdletbinding(SupportsShouldProcess)]
param
(
[Parameter(Mandatory = $true)]
[xml] $XmlDoc,
[string] $Name,
[string] $Value
)
if ( $PSCmdlet.ShouldProcess( 'ParamNode' ) )
{
$paramNode = $XmlDoc.CreateElement( 'param' )
$paramNode.SetAttribute( 'name', $Name )
$paramNode.SetAttribute( 'value', $Value )
$paramNode
}
}
function New-JobSchedulerAgentInstanceScript
{
[cmdletbinding(SupportsShouldProcess)]
param
(
[Parameter(Mandatory = $false)]
[string] $SchedulerHome,
[string] $SchedulerData,
[string] $HttpPort='127.0.0.1:4445',
[string] $HttpsPort,
[string] $LogDirectory,
[string] $PidFileDirectory,
[string] $WorkingDirectory,
[string] $KillScript,
[string] $JavaHome,
[string] $JavaOptions
)
$script = "
@echo off
rem # -----------------------------------------------------------------------
rem # Company: Software- und Organisations-Service GmbH
rem # Purpose: Instance (service) startscript for JobScheduler Agent
rem # -----------------------------------------------------------------------
SETLOCAL
rem ### USAGE OF THIS FILE ####################################
rem #
rem # This is a template for the JobScheduler Agent Instance
rem # script.
rem # It can be used as service startscript.
rem #
rem # Each instance of the JobScheduler Agent must have a
rem # different HTTP port. For example if the port 4445
rem # is used for the instance then copy this file
rem #
rem # '.\bin\jobscheduler_agent_instance.cmd-example'
rem # -> '.\bin\jobscheduler_agent_4445.cmd'
rem #
rem # and set the SCHEDULER_HTTP_PORT variable below.
rem #
rem # See also the other environment variables below.
rem #
rem ###########################################################
rem ### SETTINGS ##############################################
rem # This variable has to point to the installation path of
rem # the JobScheduler Agent.
rem # If this variable not defined then the parent directory
rem # of this startscript is used.
"
if ( $SchedulerHome )
{
$script += "
set SCHEDULER_HOME=$($SchedulerHome)
"
} else {
$script += "
rem set SCHEDULER_HOME=
"
}
$script += "
rem # The http port of the JobScheduler Agent can be set here,
rem # as command line option -http-port (see usage) or as
rem # environment variable. Otherwise the above default port
rem # is used.
rem # If only a port is specified then the JobScheduler Agent
rem # listens to all available network interfaces.
rem # It is the same like 0.0.0.0:port.
rem # Use the form <ip address or hostname>:port for indicating
rem # which network interfaces the JobScheduler Agent should
rem # listen to.
rem # The command line option -http-port beats the environment
rem # variable SCHEDULER_HTTP_PORT and the environment variable
rem # SCHEDULER_HTTP_PORT beats the default port from
rem # SCHEDULER_AGENT_DEFAULT_HTTP_PORT(=4445).
rem ### NOTE:
rem # If you start the JobScheduler Agent with the command line
rem # option -http-port then you must enter -http-port for
rem # stop, status, restart too (see usage). It's recommended
rem # to set this environment variable instead.
"
if ( $HttpPort )
{
$script += "
set SCHEDULER_HTTP_PORT=$($HttpPort)
"
} else {
$script += "
rem set SCHEDULER_HTTP_PORT=
"
}
$script += "
rem # In addition to the http port a https port of the
rem # JobScheduler Agent can be set here, as command line option
rem # -https-port (see usage) or as environment variable.
rem # If only a port is specified then the JobScheduler Agent
rem # listens to all available network interfaces.
rem # It is the same like 0.0.0.0:port.
rem # Use the form <ip address or hostname>:port for indicating
rem # which network interfaces the JobScheduler Agent should
rem # listen to.
rem # The command line option -https-port beats the environment
rem # variable SCHEDULER_HTTPS_PORT.
"
if ( $HttpsPort )
{
$script += "
set SCHEDULER_HTTPS_PORT=$($HttpsPort)
"
} else {
$script += "
rem set SCHEDULER_HTTPS_PORT=
"
}
$script += "
rem # Set the directory where the JobScheduler Agent has the
rem # configuration, logs, etc.