-
Notifications
You must be signed in to change notification settings - Fork 1
/
SCOM - Add Maintenance Mode Schedule.ps1
724 lines (587 loc) · 36.8 KB
/
SCOM - Add Maintenance Mode Schedule.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
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
#########
# au2mator PS Services
# New Service
#
# Title: SCOM - Add Maintenance Mode Schedule
#
# v 1.0 Initial Release
# v 1.1 Powershell 7 ready, v1.4 Template
#
# Init Release: 03.02.2020
# Last Update: 08.09.2021
# Code Template V 1.4
#
# URL: https://au2mator.com/add-maintenance-mode-schedule-scom-self-service-with-au2mator/
# Github: https://github.com/au2mator/SCOM-Add-Maintenance-Mode-Schedule
#
#################
#region InputParamaters
##Question in au2mator
param (
[parameter(Mandatory = $true)]
[String]$c_StartDate,
[parameter(Mandatory = $true)]
[String]$c_EndDate,
[parameter(Mandatory = $true)]
[String]$c_DA,
[parameter(Mandatory = $true)]
[String]$c_Category,
[parameter(Mandatory = $true)]
[String]$InitiatedBy,
[parameter(Mandatory = $true)]
[String]$RequestId,
[parameter(Mandatory = $true)]
[String]$Service,
[parameter(Mandatory = $true)]
[String]$TargetUserId
)
#endregion InputParamaters
#region Variables
Set-ExecutionPolicy -ExecutionPolicy Bypass
$DoImportPSSession = $false
## Environment
[string]$OpsmgrServer = 'Demo01'
[string]$LogPath = "C:\_SCOworkingDir\TFS\PS-Services\SCOM - Add Maintenance Mode Schedule"
[string]$LogfileName = "Add Maintenance Mode Schedule"
[string]$CredentialStorePath = "C:\_SCOworkingDir\TFS\PS-Services\CredentialStore" #see for details: https://click.au2mator.com/PSCreds/?utm_source=github&utm_medium=social&utm_campaign=SCOM_StartMM&utm_content=PS1
$Modules = @("ActiveDirectory") #$Modules = @("ActiveDirectory", "SharePointPnPPowerShellOnline")
## au2mator Settings
[string]$PortalURL = "http://demo01.au2mator.local"
[string]$au2matorDBServer = "demo01"
[string]$au2matorDBName = "au2mator40Demo2"
#Control Teams
$SendTeamsCardToInitiatedByUser = $true #Send a Card in Teams after Service is completed
$SendTeamsCardToTargetUser = $false #Send Card in Teams to Target User after Service is completed
$ToChannel = $true #Send the Message Card to a Channel
$ToUser = $false #Send the Message Card to the User via Chat
#Teams Settings
$TeamName = "au2mator - ORG"
$ChannelName = "General"
## Control Mail
$SendMailToInitiatedByUser = $true #Send a Mail after Service is completed
$SendMailToTargetUser = $true #Send Mail to Target User after Service is completed
## SMTP Settings
$SMTPServer = "smtp.office365.com"
$SMPTAuthentication = $true #When True, User and Password needed
$EnableSSLforSMTP = $true
$SMTPSender = "SelfService@au2mator.com"
$SMTPPort = "587"
# Stored Credentials
# See: https://click.au2mator.com/PSCreds/?utm_source=github&utm_medium=social&utm_campaign=SCOM_StartMM&utm_content=PS1
$SMTPCredential_method = "Stored" #Stored, Manual
$SMTPcredential_File = "SMTPCreds.xml"
$SMTPUser = ""
$SMTPPassword = ""
if ($SMTPCredential_method -eq "Stored") {
$SMTPcredential = Import-CliXml -Path (Get-ChildItem -Path $CredentialStorePath -Filter $SMTPcredential_File).FullName
}
if ($SMTPCredential_method -eq "Manual") {
$f_secpasswd = ConvertTo-SecureString $SMTPPassword -AsPlainText -Force
$SMTPcredential = New-Object System.Management.Automation.PSCredential ($SMTPUser, $f_secpasswd)
}
#TeamsCredentials to send Teams Card #https://click.au2mator.com/PSCreds/?utm_source=github&utm_medium=social&utm_campaign=PS_Template&utm_content=PS1
$GraphAPICred_File = "TeamsCreds.xml"
$GraphAPICred = Import-CliXml -Path (Get-ChildItem -Path $CredentialStorePath -Filter $GraphAPICred_File).FullName
$TEAMS_clientId = $GraphAPICred.clientId
$TEAMS_clientSecret = $GraphAPICred.clientSecret
$TEAMS_tenantName = $GraphAPICred.tenantName
$TEAMS_User = $GraphAPICred.User
$TEAMS_PW = $GraphAPICred.PW
#endregion Variables
#region CustomVaribles
#endregion CustomVaribles
#region Functions
function Write-au2matorLog {
[CmdletBinding()]
param
(
[ValidateSet('DEBUG', 'INFO', 'WARNING', 'ERROR')]
[string]$Type,
[string]$Text
)
# Set logging path
if (!(Test-Path -Path $logPath)) {
try {
$null = New-Item -Path $logPath -ItemType Directory
Write-Verbose ("Path: ""{0}"" was created." -f $logPath)
}
catch {
Write-Verbose ("Path: ""{0}"" couldn't be created." -f $logPath)
}
}
else {
Write-Verbose ("Path: ""{0}"" already exists." -f $logPath)
}
[string]$logFile = '{0}\{1}_{2}.log' -f $logPath, $(Get-Date -Format 'yyyyMMdd'), $LogfileName
$logEntry = '{0}: <{1}> <{2}> <{3}> {4}' -f $(Get-Date -Format dd.MM.yyyy-HH:mm:ss), $Type, $RequestId, $Service, $Text
Add-Content -Path $logFile -Value $logEntry
}
function ConnectToDB {
# define parameters
param(
[string]
$servername,
[string]
$database
)
Write-au2matorLog -Type INFO -Text "Function ConnectToDB"
# create connection and save it as global variable
$global:Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$servername';database='$database';trusted_connection=false; integrated security='true'"
$Connection.Open()
Write-au2matorLog -Type INFO -Text 'Connection established'
}
function ExecuteSqlQuery {
# define parameters
param(
[string]
$sqlquery
)
Write-au2matorLog -Type INFO -Text "Function ExecuteSqlQuery"
#Begin {
If (!$Connection) {
Write-au2matorLog -Type WARNING -Text"No connection to the database detected. Run command ConnectToDB first."
}
elseif ($Connection.State -eq 'Closed') {
Write-au2matorLog -Type INFO -Text 'Connection to the database is closed. Re-opening connection...'
try {
# if connection was closed (by an error in the previous script) then try reopen it for this query
$Connection.Open()
}
catch {
Write-au2matorLog -Type INFO -Text "Error re-opening connection. Removing connection variable."
Remove-Variable -Scope Global -Name Connection
Write-au2matorLog -Type WARNING -Text "Unable to re-open connection to the database. Please reconnect using the ConnectToDB commandlet. Error is $($_.exception)."
}
}
#}
#Process {
#$Command = New-Object System.Data.SQLClient.SQLCommand
$command = $Connection.CreateCommand()
$command.CommandText = $sqlquery
Write-au2matorLog -Type INFO -Text "Running SQL query '$sqlquery'"
try {
$result = $command.ExecuteReader()
}
catch {
$Connection.Close()
}
$Datatable = New-Object "System.Data.Datatable"
$Datatable.Load($result)
return $Datatable
#}
#End {
Write-au2matorLog -Type INFO -Text "Finished running SQL query."
#}
}
function Get-UserInput ($RequestID) {
[hashtable]$return = @{ }
Write-au2matorLog -Type INFO -Text "Function Get-UserInput"
ConnectToDB -servername $au2matorDBServer -database $au2matorDBName
$Result = ExecuteSqlQuery -sqlquery "SELECT RPM.Text AS Question, RP.Value
FROM dbo.Requests AS R INNER JOIN
dbo.RunbookParameterMappings AS RPM ON R.ServiceId = RPM.ServiceId INNER JOIN
dbo.RequestParameters AS RP ON RPM.ParameterName = RP.[Key] AND R.ID = RP.RequestId
where RP.RequestId = '$RequestID' and rpm.IsDeleted = '0' order by [Order]"
$html = "<table><tr><td><b>Question</b></td><td><b>Answer</b></td></tr>"
$html = "<table>"
foreach ($row in $Result) {
#$row
$html += "<tr><td><b>" + $row.Question + ":</b></td><td>" + $row.Value + "</td></tr>"
}
$html += "</table>"
$f_RequestInfo = ExecuteSqlQuery -sqlquery "select InitiatedBy, TargetUserId,[ApprovedBy], [ApprovedTime], Comment from Requests where Id = '$RequestID'"
$Connection.Close()
Remove-Variable -Scope Global -Name Connection
$f_SamInitiatedBy = $f_RequestInfo.InitiatedBy.Split("\")[1]
$f_UserInitiatedBy = Get-ADUser -Identity $f_SamInitiatedBy -Properties Mail
$f_SamTarget = $f_RequestInfo.TargetUserId.Split("\")[1]
$f_UserTarget = Get-ADUser -Identity $f_SamTarget -Properties Mail
$return.InitiatedBy = $f_RequestInfo.InitiatedBy.trim()
$return.MailInitiatedBy = $f_UserInitiatedBy.mail.trim()
$return.MailTarget = $f_UserTarget.mail.trim()
$return.TargetUserId = $f_RequestInfo.TargetUserId.trim()
$return.ApprovedBy = $f_RequestInfo.ApprovedBy.trim()
$return.ApprovedTime = $f_RequestInfo.ApprovedTime
$return.Comment = $f_RequestInfo.Comment
$return.HTML = $HTML
return $return
}
Function Get-MailContent ($RequestID, $RequestTitle, $EndDate, $TargetUserId, $InitiatedBy, $Status, $PortalURL, $RequestedBy, $AdditionalHTML, $InputHTML) {
Write-au2matorLog -Type INFO -Text "Function Get-MailContent"
$f_RequestID = $RequestID
$f_InitiatedBy = $InitiatedBy
$f_RequestTitle = $RequestTitle
try {
$f_EndDate = (get-Date -Date $EndDate -Format (Get-Culture).DateTimeFormat.ShortDatePattern) + " (" + (get-Date -Date $EndDate -Format (Get-Culture).DateTimeFormat.ShortTimePattern) + ")"
}
catch {
$f_EndDate = $EndDate
}
$f_RequestStatus = $Status
$f_RequestLink = "$PortalURL/requeststatus?id=$RequestID"
$f_HTMLINFO = $AdditionalHTML
$f_InputHTML = $InputHTML
$f_SamInitiatedBy = $f_InitiatedBy.Split("\")[1]
$f_UserInitiatedBy = Get-ADUser -Identity $f_SamInitiatedBy -Properties DisplayName
$f_DisplaynameInitiatedBy = $f_UserInitiatedBy.DisplayName
$HTML = @'
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 1.5pt; background: #F7F8F3; mso-yfti-tbllook: 1184;" border="0" width="100%" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes; mso-yfti-lastrow: yes;">
<td style="padding: .75pt .75pt .75pt .75pt;" valign="top"> </td>
<td style="width: 450.0pt; padding: .75pt .75pt .75pt .75pt; box-sizing: border-box;" valign="top" width="600">
<div style="box-sizing: border-box;">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; background: white; border: solid #E9E9E9 1.0pt; mso-border-alt: solid #E9E9E9 .75pt; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm;" border="1" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes;">
<td style="border: none; background: #6ddc36; padding: 15.0pt 0cm 15.0pt 15.0pt;" valign="top">
<p class="MsoNormal" style="line-height: 19.2pt;"><img src="https://au2mator.com/wp-content/uploads/2018/02/HPLogoau2mator-1.png" alt="" width="198" height="43" /></p>
</td>
</tr>
<tr style="mso-yfti-irow: 1; box-sizing: border-box;">
<td style="border: none; padding: 15.0pt 15.0pt 15.0pt 15.0pt; box-sizing: border-box;" valign="top">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm; box-sizing: border-box;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes; mso-yfti-lastrow: yes; box-sizing: border-box;">
<td style="padding: 0cm 0cm 15.0pt 0cm; box-sizing: border-box;" valign="top">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm; box-sizing: border-box;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes; mso-yfti-lastrow: yes; box-sizing: border-box;">
<td style="width: 55.0%; padding: 0cm 0cm 0cm 0cm; box-sizing: border-box;" valign="top" width="55%">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes;">
<td style="width: 18.75pt; border-top: solid #E3E3E3 1.0pt; border-left: solid #E3E3E3 1.0pt; border-bottom: none; border-right: none; mso-border-top-alt: solid #E3E3E3 .75pt; mso-border-left-alt: solid #E3E3E3 .75pt; padding: 0cm 0cm 0cm 0cm; box-sizing: border-box;" width="25">
<p class="MsoNormal" style="text-align: center; line-height: 19.2pt;" align="center"> </p>
</td>
<td style="border-top: solid #E3E3E3 1.0pt; border-left: none; border-bottom: none; border-right: solid #E3E3E3 1.0pt; mso-border-top-alt: solid #E3E3E3 .75pt; mso-border-right-alt: solid #E3E3E3 .75pt; padding: 0cm 0cm 3.75pt 0cm; font-color: #0000;"><strong>End Date</strong>: ##EndDate</td>
</tr>
<tr style="mso-yfti-irow: 1;">
<td style="border-top: solid #E3E3E3 1.0pt; border-left: solid #E3E3E3 1.0pt; border-bottom: none; border-right: none; mso-border-top-alt: solid #E3E3E3 .75pt; mso-border-left-alt: solid #E3E3E3 .75pt; padding: 0cm 0cm 0cm 0cm;">
<p class="MsoNormal" style="text-align: center; line-height: 19.2pt;" align="center"> </p>
</td>
<td style="border-top: solid #E3E3E3 1.0pt; border-left: none; border-bottom: none; border-right: solid #E3E3E3 1.0pt; mso-border-top-alt: solid #E3E3E3 .75pt; mso-border-right-alt: solid #E3E3E3 .75pt; padding: 0cm 0cm 3.75pt 0cm;"><strong>Status</strong>: ##Status</td>
</tr>
<tr style="mso-yfti-irow: 2; mso-yfti-lastrow: yes;">
<td style="border: solid #E3E3E3 1.0pt; border-right: none; mso-border-top-alt: solid #E3E3E3 .75pt; mso-border-left-alt: solid #E3E3E3 .75pt; mso-border-bottom-alt: solid #E3E3E3 .75pt; padding: 0cm 0cm 3.75pt 0cm;">
<p class="MsoNormal" style="text-align: center; line-height: 19.2pt;" align="center"> </p>
</td>
<td style="border: solid #E3E3E3 1.0pt; border-left: none; mso-border-top-alt: solid #E3E3E3 .75pt; mso-border-bottom-alt: solid #E3E3E3 .75pt; mso-border-right-alt: solid #E3E3E3 .75pt; padding: 0cm 0cm 3.75pt 0cm;"><strong>Requested By</strong>: ##RequestedBy</td>
</tr>
</tbody>
</table>
</td>
<td style="width: 5.0%; padding: 0cm 0cm 0cm 0cm; box-sizing: border-box;" width="5%">
<p class="MsoNormal" style="line-height: 19.2pt;"><span style="font-size: 9.0pt; font-family: 'Helvetica',sans-serif; mso-fareast-font-family: 'Times New Roman';"> </span></p>
</td>
<td style="width: 40.0%; padding: 0cm 0cm 0cm 0cm; box-sizing: border-box;" valign="top" width="40%">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; background: #FAFAFA; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes; mso-yfti-lastrow: yes;">
<td style="width: 100.0%; border: solid #E3E3E3 1.0pt; mso-border-alt: solid #E3E3E3 .75pt; padding: 7.5pt 0cm 1.5pt 3.75pt;" width="100%">
<p style="text-align: center;" align="center"><span style="font-size: 10.5pt; color: #959595;">au2mator Request ID</span></p>
<p style="text-align: center;" align="center"><u><span style="font-size: 12.0pt; color: black;"><a href="##RequestLink"><span style="color: black;">##REQUESTID</span></a></span></u></p>
<p class="MsoNormal" style="text-align: center;" align="center"><span style="mso-fareast-font-family: 'Times New Roman';"> </span></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="mso-yfti-irow: 2; box-sizing: border-box;">
<td style="border: none; padding: 0cm 15.0pt 15.0pt 15.0pt; box-sizing: border-box;" valign="top">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm; box-sizing: border-box;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes; box-sizing: border-box;">
<td style="padding: 0cm 0cm 15.0pt 0cm; box-sizing: border-box;" valign="top">
<p class="MsoNormal" style="line-height: 19.2pt;"><strong><span style="font-size: 10.5pt; font-family: 'Helvetica',sans-serif; mso-fareast-font-family: 'Times New Roman';">Dear ##UserDisplayname,</span></strong></p>
</td>
</tr>
<tr style="mso-yfti-irow: 1; box-sizing: border-box;">
<td style="padding: 0cm 0cm 15.0pt 0cm; box-sizing: border-box;" valign="top">
<p class="MsoNormal" style="line-height: 19.2pt;"><span style="font-size: 10.5pt; font-family: 'Helvetica',sans-serif; mso-fareast-font-family: 'Times New Roman';">We finished the Request <strong>"##RequestTitle"</strong>!<br /> <br /> Here are the Result of the Request:<br /><b>##HTMLINFO </b><br /></span></p>
<div> </div>
<div>See the details of the Request</div>
<div>##InputHTML</div>
<div> </div>
<div> </div>
Kind regards,<br /> au2mator Self Service Team
<p> </p>
</td>
</tr>
<tr style="mso-yfti-irow: 2; mso-yfti-lastrow: yes; box-sizing: border-box;">
<td style="padding: 0cm 0cm 15.0pt 0cm; box-sizing: border-box;" valign="top">
<p class="MsoNormal" style="text-align: center; line-height: 19.2pt;" align="center"><span style="font-size: 10.5pt; font-family: 'Helvetica',sans-serif; mso-fareast-font-family: 'Times New Roman';"><a style="border-radius: 3px; -webkit-border-radius: 3px; -moz-border-radius: 3px; display: inline-block;" href="##RequestLink"><strong><span style="color: white; border: solid #50D691 6.0pt; padding: 0cm; background: #50D691; text-decoration: none; text-underline: none;">View your Request</span></strong></a></span></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr style="mso-yfti-irow: 3; mso-yfti-lastrow: yes; box-sizing: border-box;">
<td style="border: none; padding: 0cm 0cm 0cm 0cm; box-sizing: border-box;" valign="top">
<table class="MsoNormalTable" style="width: 100.0%; mso-cellspacing: 0cm; background: #333333; mso-yfti-tbllook: 1184; mso-padding-alt: 0cm 0cm 0cm 0cm;" border="0" width="100%" cellspacing="0" cellpadding="0">
<tbody>
<tr style="mso-yfti-irow: 0; mso-yfti-firstrow: yes; mso-yfti-lastrow: yes; box-sizing: border-box;">
<td style="width: 50.0%; border: none; border-right: solid lightgrey 1.0pt; mso-border-right-alt: solid lightgrey .75pt; padding: 22.5pt 15.0pt 22.5pt 15.0pt; box-sizing: border-box;" valign="top" width="50%"> </td>
<td style="width: 50.0%; padding: 22.5pt 15.0pt 22.5pt 15.0pt; box-sizing: border-box;" valign="top" width="50%"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
<td style="padding: .75pt .75pt .75pt .75pt; box-sizing: border-box;" valign="top"> </td>
</tr>
</tbody>
</table>
<p class="MsoNormal"><span style="mso-fareast-font-family: 'Times New Roman';"> </span></p>
'@
$html = $html.replace('##REQUESTID', $f_RequestID).replace('##UserDisplayname', $f_DisplaynameInitiatedBy).replace('##RequestTitle', $f_RequestTitle).replace('##EndDate', $f_EndDate).replace('##Status', $f_RequestStatus).replace('##RequestedBy', $f_InitiatedBy).replace('##HTMLINFO', $f_HTMLINFO).replace('##InputHTML', $f_InputHTML).replace('##RequestLink', $f_RequestLink)
return $html
}
Function Send-ServiceMail ($HTMLBody, $ServiceName, $Recipient, $RequestID, $RequestStatus) {
Write-au2matorLog -Type INFO -Text "Function Send-ServiceMail"
$f_Subject = "au2mator - $ServiceName Request [$RequestID] - $RequestStatus"
Write-au2matorLog -Type INFO -Text "Subject: $f_Subject "
Write-au2matorLog -Type INFO -Text "Recipient: $Recipient"
try {
if ($SMPTAuthentication) {
if ($EnableSSLforSMTP) {
Write-au2matorLog -Type INFO -Text "Run SMTP with Authentication and SSL"
Send-MailMessage -SmtpServer $SMTPServer -To $Recipient -From $SMTPSender -Subject $f_Subject -Body $HTMLBody -BodyAsHtml -Priority high -Credential $SMTPcredential -UseSsl -Port $SMTPPort
}
else {
Write-au2matorLog -Type INFO -Text "Run SMTP with Authentication and no SSL"
Send-MailMessage -SmtpServer $SMTPServer -To $Recipient -From $SMTPSender -Subject $f_Subject -Body $HTMLBody -BodyAsHtml -Priority high -Credential $SMTPcredential -Port $SMTPPort
}
}
else {
if ($EnableSSLforSMTP) {
Write-au2matorLog -Type INFO -Text "Run SMTP without Authentication and SSL"
Send-MailMessage -SmtpServer $SMTPServer -To $Recipient -From $SMTPSender -Subject $f_Subject -Body $HTMLBody -BodyAsHtml -Priority high -UseSsl -Port $SMTPPort
}
else {
Write-au2matorLog -Type INFO -Text "Run SMTP without Authentication and no SSL"
Send-MailMessage -SmtpServer $SMTPServer -To $Recipient -From $SMTPSender -Subject $f_Subject -Body $HTMLBody -BodyAsHtml -Priority high -Port $SMTPPort
}
}
}
catch {
Write-au2matorLog -Type WARNING -Text "Error on sending Mail"
Write-au2matorLog -Type WARNING -Text $Error
}
}
Function Send-TeamsCard ($ServiceName, $Recipient, $RequestID, $RequestStatus, $au2matorReturn) {
Write-au2matorLog -Type INFO -Text "Function Send Teams Card"
switch ($RequestStatus) {
"COMPLETED" { $statusColor = "Good" }
"IN PROGRESS" { $statusColor = "Accent" }
"ERROR" { $statusColor = "Attention" }
"FAILED" { $statusColor = "Attention" }
"WARNING" { $statusColor = "Warning" }
Default { $statusColor = "Good" }
}
Write-au2matorLog -Type INFO -Text "Calculated the Statuscolor: $statusColor related to our Status: $RequestStatus"
$URL = $PortalURL + "/Requests/SingleStatus?id=$RequestID"
#Connect to GRAPH API
$tokenBody = @{
Grant_Type = "password"
Scope = "user.read%20openid%20profile%20offline_access"
Client_Id = $TEAMS_clientId
username = $TEAMS_User
password = $TEAMS_pw
resource = "https://graph.microsoft.com"
}
$tokenResponse = Invoke-RestMethod "https://login.microsoftonline.com/common/oauth2/token" -Method Post -ContentType "application/x-www-form-urlencoded" -Body $tokenBody -ErrorAction STOP
$headers = @{
"Authorization" = "Bearer $($tokenResponse.access_token)"
"Content-type" = "application/json"
}
$GUID = (New-Guid).guid
$GetRecipientUserURL = "https://graph.microsoft.com/v1.0/users/$Recipient"
$RecipientUserID = (Invoke-RestMethod -Uri $GetRecipientUserURL -Method GET -Headers $headers).id
$RecipientUserDisplayName = (Invoke-RestMethod -Uri $GetRecipientUserURL -Method GET -Headers $headers).displayname
if ($ToChannel) {
Write-au2matorLog -Type INFO -Text "Send Card to Channel"
#Get ID for the Team
$URLgetteamid = "https://graph.microsoft.com/v1.0/groups?$select=id,resourceProvisioningOptions,displayName"
$TeamID = ((Invoke-RestMethod -Method GET -Uri $URLgetteamid -Headers $headers).value | Where-Object -property displayName -value $TeamName -eq).id
#Get ID for the Channel
$URLgetchannelid = "https://graph.microsoft.com/v1.0/teams/$TeamID/channels"
$ChannelID = ((Invoke-RestMethod -Method GET -Uri $URLgetchannelid -Headers $headers).value | Where-Object -property displayName -value $ChannelName -eq).id
#Send Message in channel
$URLchatmessage = "https://graph.microsoft.com/v1.0/teams/$TeamID/channels/$ChannelID/messages"
}
if ($ToUser) {
Write-au2matorLog -Type INFO -Text "Send Card to User"
$GetBotUserURL = "https://graph.microsoft.com/v1.0/users/$TEAMS_User"
$BotUserID = (Invoke-RestMethod -Uri $GetBotUserURL -Method GET -Headers $headers).id
$ChatBody = @"
{
"chatType": "oneOnOne",
"members": [
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user@odata.bind": "https://graph.microsoft.com/v1.0/users('$BotUserID')"
},
{
"@odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user@odata.bind": "https://graph.microsoft.com/v1.0/users('$RecipientUserID')"
}
]
}
"@
$URLchat = "https://graph.microsoft.com/v1.0/Chats"
$ChatID = (Invoke-RestMethod -Uri $URLchat -Method POST -Body $ChatBody -Headers $headers).id
$URLchatmessage = "https://graph.microsoft.com/v1.0/Chats/$ChatID/messages"
}
$BodyJsonTeam = @"
{
"subject": null,
"body": {
"contentType": "html",
"content": "<attachment id=\"$GUID\"></attachment>"
},
"attachments": [
{
"id": "$GUID",
"contentType": "application/vnd.microsoft.card.adaptive",
"content": "{\n \"type\": \"AdaptiveCard\",\n \"$schema\": \"http://adaptivecards.io/schemas/adaptive-card.json\",\n \"version\": \"1.2\",\n \"speak\": \"<s>au2mator Request ID $RequestID is $RequestStatus</s><s>$au2matorReturn</s>\",\n \"body\": [\n {\n \"type\": \"TextBlock\",\n \"text\": \"Hi <at>$RecipientUserDisplayName</at>, \\nhere is the Result of your au2mator Service\",\n \"wrap\": true,\n \"w eight\": \"Bolder\",\n \"fontType\": \"Default\"\n },{\n \"type\": \"ColumnSet\",\n \"columns\": [\n {\n \"type\": \"Column\",\n \"width\": \"auto\",\n \"items\": [\n {\n \"type\": \"Image\",\n \"url\": \"https://au2mator.com/wp-content/uploads/2018/02/HPLogoau2mator-1.png\",\n \"altText\": \"au2mator Logo\"\n }\n ]\n},\n {\n \"type\": \"Column\",\n \"width\": \"stretch\",\n \"items\": [\n {\n \"type\": \"TextBlock\",\n \"text\": \"Status\",\n \"horizontalAlignment\": \"Right\",\n \"isSubtle\": true,\n \"wrap\": true\n },\n {\n \"type\": \"TextBlock\",\n \"text\": \"$RequestStatus\",\n \"horizontalAlignment\": \"Right\",\n \"spacing\": \"None\",\n \"size\": \"Large\",\n \"wrap\": true,\n \"color\": \"$statusColor\"\n}\n ]\n }\n ]\n },\n {\n \"type\": \"ColumnSet\",\n \"separator\": true,\n \"spacing\": \"Medium\",\n \"columns\": [\n {\n \"type\": \"Column\",\n \"width\": \"stretch\",\n \"items\": [\n {\n \"type\": \"TextBlock\",\n \"text\": \"ServiceName\",\n \"wrap\": true\n },\n {\n \"type\": \"TextBlock\",\n \"text\": \"RequestID\",\n \"wrap\": true\n }\n ]\n },\n {\n \"type\": \"Column\",\n \"width\": \"auto\",\n \"items\": [\n {\n \"type\": \"TextBlock\",\n \"horizontalAlignment\": \"Right\",\n \"isSubtle\": true,\n \"weight\": \"Bolder\",\n \"wrap\": true,\n \"text\": \"$ServiceName \"\n },\n {\n \"type\": \"TextBlock\",\n \"text\": \"$RequestID\",\n \"horizontalAlignment\": \"Right\",\n \"spacing\": \"Small\",\n \"wrap\": true\n }\n ]\n }\n ]\n },\n {\n\"type\": \"ColumnSet\",\n \"spacing\": \"Medium\",\n \"separator\": true,\n \"columns\": [\n {\n \"type\": \"Column\",\n \"width\": 1,\n \"items\": [\n {\n \"type\": \"TextBlock\",\n \"text\": \"Request Return\",\n \"isSubtle\": true,\n \"weight\": \"Bolder\",\n \"wrap\": true\n }\n ]\n }\n ]\n },\n {\n\"type\": \"ColumnSet\",\n \"spacing\": \"Small\",\n \"columns\": [\n {\n \"type\": \"Column\",\n \"width\": 1,\n \"items\": [\n {\n \"type\": \"TextBlock\",\n \"text\": \"$au2matorReturn \\n \",\n\"isSubtle\": true,\n \"wrap\": true\n },\n {\n \"type\": \"ActionSet\",\n \"actions\": [\n {\n \"type\": \"Action.OpenUrl\",\n \"title\": \"Request Details\",\n \"url\": \"$URL\",\n \"style\": \"destructive\"\n }\n ],\n \"height\": \"stretch\"\n}\n ]\n }\n ]\n }\n ],\n \"msteams\": {\n \"entities\": [\n {\n \"type\": \"mention\",\n \"text\": \"\u003cat\u003e$RecipientUserDisplayName\u003c/at\u003e\",\n \"mentioned\": {\n \"id\": \"8:orgid:$RecipientUserID\",\n \"name\": \"$RecipientUserDisplayName\"\n }\n }\n ]\n }\n }"
}
]
}
"@
Write-au2matorLog -Type INFO -Text "Send Card"
$Result = Invoke-RestMethod -Method POST -Uri $URLchatmessage -Body $BodyJsonTeam -Headers $headers
}
#endregion Functions
#region CustomFunctions
#endregion CustomFunctions
#region Script
Write-au2matorLog -Type INFO -Text "Start Script"
if ($DoImportPSSession) {
Write-au2matorLog -Type INFO -Text "Import-Pssession"
$PSSession = New-PSSession -ComputerName $PSRemotingServer
Import-PSSession -Session $PSSession -DisableNameChecking -AllowClobber
}
#Check for Modules if installed
Write-au2matorLog -Type INFO -Text "Try to install all PowerShell Modules"
foreach ($Module in $Modules) {
if (Get-Module -ListAvailable -Name $Module) {
Write-au2matorLog -Type INFO -Text "Module is already installed: $Module"
}
else {
Write-au2matorLog -Type INFO -Text "Module is not installed, try simple method: $Module"
try {
Install-Module $Module -Force -Confirm:$false
Write-au2matorLog -Type INFO -Text "Module was installed the simple way: $Module"
}
catch {
Write-au2matorLog -Type INFO -Text "Module is not installed, try the advanced way: $Module"
try {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module $Module -Force -Confirm:$false
Write-au2matorLog -Type INFO -Text "Module was installed the advanced way: $Module"
}
catch {
Write-au2matorLog -Type ERROR -Text "could not install module: $Module"
$au2matorReturn = "could not install module: $Module, Error: $Error"
$AdditionalHTML = "could not install module: $Module, Error: $Error
"
$Status = "ERROR"
}
}
}
Write-au2matorLog -Type INFO -Text "Import Module: $Module"
Import-module $Module
}
#region CustomCode
Write-au2matorLog -Type INFO -Text "Start Custom Code"
$error.Clear()
Write-au2matorLog -Type INFO -Text "Import Module im Compadible Mode"
Import-Module OperationsManager -UseWindowsPowerShell
Write-au2matorLog -Type INFO -Text "Try to Add Maintenance Schedule"
try {
$duration = New-TimeSpan -Start $c_StartDate -End $c_EndDate | Select-Object -ExpandProperty TotalMinutes
Write-au2matorLog -Type INFO -Text "Calculated Duration: $duration"
try {
$ClassID = (Get-SCOMClassInstance -DisplayName $c_DA | Select-Object -First 1 ID).ID.guid
Write-au2matorLog -Type INFO -Text "Queried Class ID: $ClassID"
try {
New-SCOMMaintenanceSchedule -Name "au2mator RequestID: $RequestID" -ActiveStartTime $c_StartDate -ActiveEndDate $c_EndDate -MonitoringObjects $ClassID -Duration $duration -ReasonCode $c_Category -FreqType 1 -Enabled
Write-au2matorLog -Type INFO -Text "Maintenance Schedule added for $c_DA"
$au2matorReturn = "Maintenance Schedule added for $c_DA"
$TeamsReturn = "Maintenance Schedule added for $c_DA" #No Special Characters allowed
$AdditionalHTML = "Maintenance Schedule added for $c_DA
"
$Status = "COMPLETED"
}
catch {
Write-au2matorLog -Type ERROR -Text "Failed to add Schedule"
$au2matorReturn = "Failed to add Schedule"
$TeamsReturn = "Failed to add Schedule" #No Special Characters allowed
$AdditionalHTML = "Failed to add Schedule
"
$Status = "ERROR"
}
}
catch {
Write-au2matorLog -Type ERROR -Text "Failed to get Class ID"
$au2matorReturn = "Failed to get Class ID"
$TeamsReturn = "Failed to get Class ID" #No Special Characters allowed
$AdditionalHTML = "Failed to get Class ID
"
$Status = "ERROR"
}
}
catch {
Write-au2matorLog -Type ERROR -Text "Failed to calculate Time Span"
$au2matorReturn = "Failed to calculate Time Span"
$TeamsReturn = "Failed to calculate Time Span" #No Special Characters allowed
$AdditionalHTML = "Failed to calculate Time Span
"
$Status = "ERROR"
}
#endregion CustomCode
#endregion Script
#region Return
Write-au2matorLog -Type INFO -Text "Service finished"
if ($SendMailToInitiatedByUser -or $SendMailToTargetUser -or $SendTeamsCardToInitiatedByUser -or $SendTeamsCardToTargetUser) {
Write-au2matorLog -Type INFO -Text "We need to Send Mail or Teams Chat, so get all Infos"
$UserInput = Get-UserInput -RequestID $RequestId
$HTML = Get-MailContent -RequestID $RequestId -RequestTitle $Service -EndDate $UserInput.ApprovedTime -TargetUserId $UserInput.TargetUserId -InitiatedBy $UserInput.InitiatedBy -Status $Status -PortalURL $PortalURL -AdditionalHTML $AdditionalHTML -InputHTML $UserInput.html
}
if ($SendMailToInitiatedByUser) {
Write-au2matorLog -Type INFO -Text "Send Mail to Initiated By User"
Send-ServiceMail -HTMLBody $HTML -RequestID $RequestId -Recipient $($UserInput.MailInitiatedBy) -RequestStatus $Status -ServiceName $Service
}
if ($SendMailToTargetUser) {
Write-au2matorLog -Type INFO -Text "Send Mail to Target User"
Send-ServiceMail -HTMLBody $HTML -RequestID $RequestId -Recipient $($UserInput.MailTarget) -RequestStatus $Status -ServiceName $Service
}
if ($SendTeamsCardToInitiatedByUser) {
Write-au2matorLog -Type INFO -Text "Send Teams Card to InitiatedBy"
Send-TeamsCard -RequestID $RequestId -Recipient $($UserInput.MailInitiatedBy) -RequestStatus $Status -ServiceName $Service -au2matorReturn $TeamsReturn
}
if ($SendTeamsCardToTargetUser) {
Write-au2matorLog -Type INFO -Text "Send Teams Card to Target User"
Send-TeamsCard -RequestID $RequestId -Recipient $($UserInput.MailTarget) -RequestStatus $Status -ServiceName $Service -au2matorReturn $TeamsReturn
}
return $au2matorReturn
#endregion Return