Repository navigation
Expand file tree
/
Copy pathSend-DeviceMaintenaceWindowsGeneric.ps1
More file actions
528 lines (391 loc) · 15.3 KB
/
Copy pathSend-DeviceMaintenaceWindowsGeneric.ps1
File metadata and controls
528 lines (391 loc) · 15.3 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
522
523
524
525
526
527
528
<#
-------------------------------------------------------------------------------------------------------------------------
.Synopsis
Generate htmlpage with Devices and Maintenance Windows
.DESCRIPTION
Script to be run as schedule task on siteserver.
The script generate a html-page and if you use the send-mailkitmessage it will send a mail
to a group of administrators with info about the Maintenace Windows for a devices in a
collection.
.EXAMPLE
Send-DeviceMaintenanceWindows.ps1
.DISCLAIMER
All scripts and other Powershell references are offered AS IS with no warranty.
These script and functions are tested in my environment and it is recommended that you test these scripts in a test environment before using in your production environment.
-------------------------------------------------------------------------------------------------------------------------
#>
<#
===========================================================================
Values needed to be updated before running the script
===========================================================================
#>
$scriptversion = '1.0'
$scriptname = $MyInvocation.MyCommand.Name
[System.Xml.XmlDocument]$xml = Get-Content .\ScriptConfig.xml
$siteserver = $xml.Configuration.SiteServer
$DaysAfterPatchTuesdayToReport = '7'
#$DaysAfterPatchTuesdayToReport = '2'
$DisableReport = ""
$filedate = get-date -Format yyyMMdd
$HTMLFileSavePath = "G:\Scripts\Outfiles\VXOPS_MW_$filedate.HTML"
$CSVFileSavePath = "G:\Scripts\Outfiles\VXOPS_MW_$filedate.csv"
$SMTP = $xml.Configuration.MailSMTP
$MailFrom = $xml.Configuration.Mailfrom
$MailPortnumber = $xml.Configuration.MailPort
$MailCustomer = $xml.Configuration.MailCustomer
$collectionidToCheck = 'VP100021'
$Logfile = "G:\Scripts\Logfiles\WindowsUpdateScript.log"
$logfile_MW = "G:\Scripts\Logfiles\MW_Script_$filedate.log"
function Write-Log
{
Param ([string]$LogString)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp $LogString"
Add-content $LogFile -value $LogMessage
}
function Write-MWLog
{
Param ([string]$LogString)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$LogMessage = "$Stamp $LogString"
Add-content $logfile_MW -value $LogMessage
}
function Rotate-log
{
$target = Get-ChildItem $Logfile -Filter "windows*.log"
$threshold = 30
$datetime = Get-Date -uformat "%Y-%m-%d-%H%M"
$target | ForEach-Object {
if ($_.Length -ge $threshold) {
Write-Host "file named $($_.name) is bigger than $threshold KB"
$newname = "$($_.BaseName)_${datetime}.log_old"
Rename-Item $_.fullname $newname
Write-Host "Done rotating file"
}
else{
Write-Host "file named $($_.name) is not bigger than $threshold KB"
}
Write-Host " "
}
}
<#
===========================================================================
Powershell modules needed in the script
===========================================================================
Send-MailkitMessage - https://github.com/austineric/Send-MailKitMessage
pswritehtml - https://github.com/EvotecIT/PSWriteHTML
PatchManagementSupportTools - Created by Christian Damberg, Cygate
https://github.com/DambergC/PatchManagement/tree/main/PatchManagementSupportTools
DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!
#>
#region modules
if (-not (Get-Module -name send-mailkitmessage))
{
#Install-Module send-mailkitmessage -ErrorAction SilentlyContinue
Import-Module send-mailkitmessage
}
if (-not (Get-Module -name PSWriteHTML))
{
#Install-Module PSWriteHTML -ErrorAction SilentlyContinue
Import-Module PSWriteHTML
}
if (-not (Get-Module -name PatchManagementSupportTools))
{
#Install-Module PatchManagementSupportTools -ErrorAction SilentlyContinue
Import-Module PatchManagementSupportTools
}
#endregion
function Get-CMSiteCode
{
$CMSiteCode = Get-WmiObject -Namespace "root\SMS" -Class SMS_ProviderLocation -ComputerName $SiteServer | Select-Object -ExpandProperty SiteCode
return $CMSiteCode
}
Get-CMModule
#Write-Log -LogString "Send-DeviceMaintenanceWindows - CMmodule imported"
$sitecode = get-cmsitecode
#Write-Log -LogString "Send-DeviceMaintenanceWindows - $sitecode extracted"
$SetSiteCode = $sitecode + ":"
Set-Location $SetSiteCode
#Write-Log -LogString "Send-DeviceMaintenanceWindows - set location to $SetSiteCode"
<#
===========================================================================
Date-section
DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!DON´T EDIT!!!
===========================================================================
#>
$todayDefault = Get-Date
$todayshort = $todayDefault.ToShortDateString()
$thismonth = $todaydefault.Month
$nextmonth = $todaydefault.Month + 1
$patchtuesdayThisMonth = Get-PatchTuesday -Month $thismonth -Year $todayDefault.Year
$checkdatestart = $patchtuesdayThisMonth.ToShortDateString()
$ReportdayCompare = $patchtuesdayThisMonth.AddDays($DaysAfterPatchTuesdayToReport)
$ReportdayCompareShort = $ReportdayCompare.ToShortDateString()
#Write-Log -LogString "TEST $test"
#$nextyear = $todayDefault.Year + 1
If ($nextmonth -eq 13)
{
$nextmonth = '1'
$nextyear = ((get-date).Year) +1
$patchtuesdayNextMonth = Get-PatchTuesday -Month $nextmonth -Year $nextyear
$checkdateend = $patchtuesdayNextMonth.ToShortDateString()
}
else
{
$todayDefault = Get-Date
$todayshort = $todayDefault.ToShortDateString()
$thismonth = $todaydefault.Month
$nextmonth = $todaydefault.Month + 1
$thisYear = ((get-date).Year)
$patchtuesdayNextMonth = Get-PatchTuesday -Month $nextmonth -Year $thisyear
$checkdateend = $patchtuesdayNextMonth.ToShortDateString()
}
$TitleDate = get-date -DisplayHint Date
$counter = 0
#check if script should run or not
if($todayDefault.Month -in $DisableReport)
{
#write-host "date not equal"
Write-Log -LogString "Send-DeviceMaintenanceWindows - This month is skipped"
#write-host -ForegroundColor Green "This month the updates will not be installed"
set-location $PSScriptRoot
exit
}
#Region Script part 1 collect info from selected collection and check devices membership in Collections with Maintenance Windows
if ($todayshort -eq $ReportdayCompareShort)
{
# Array to collect data in
$ResultColl = @()
$ResultMissing = @()
# Devices
Write-Log -LogString "$scriptname - Date is correct, will run script"
$devices = Get-CMCollectionMember -CollectionId $collectionidToCheck
# For the progressbar
$complete = 0
# Loop for each device
foreach ($device in $devices)
{
$counter++
Write-Progress -Activity 'Processing computer' -CurrentOperation $device.Name -PercentComplete (($counter / $devices.count) * 100)
Start-Sleep -Milliseconds 100
$Devicename = $device.name
$Computertotal = $devices.Count
Write-MWLog -LogString "$scriptname - Processing computer...$Devicename - $counter of $Computertotal"
# Get all Collections for Device
try
{
$collectionids = Get-CMClientDeviceCollectionMembership -ComputerName $Devicename -SiteServer $siteserver -SiteCode $sitecode
}
catch
{
Write-Log -LogString "Can´t get any collectionid for $Devicename $_"
}
# Check every Collection for Maintenance windows
foreach ($collectionid in $collectionids)
{
# Only include Collections with Maintenance Windows
if ($collectionid.ServiceWindowsCount -gt 0)
{
$MWs = Get-CMMaintenanceWindow -CollectionId $collectionid.CollectionID
foreach ($mw in $MWs)
{
if ($mw.RecurrenceType -eq 1)
{
# Only show Maintenance Windows waiting to run
if ($mw.StartTime -gt $patchtuesdayThisMonth -and $mw.StartTime -lt $patchtuesdayNextMonth)
{
$computername = $device.Name
#$query = "SELECT applikation FROM tblinmatning WHERE skrotad=0 AND servernamn='$Computername'"
#Write-MWLog -LogString "Query against extra db run $computername"
#$data = Invoke-Sqlcmd -ServerInstance $dbserver -Database serverlista -Query $query
$Startdatum = ($mw.StartTime).ToString("yyyy-MM-dd")
$starttid = ($mw.StartTime).ToString("hh:mm")
$object = New-Object -TypeName PSObject
#$object | Add-Member -MemberType NoteProperty -Name 'Applikation' -Value $data.applikation
$object | Add-Member -MemberType NoteProperty -Name 'Server' -Value $device.name
$object | Add-Member -MemberType NoteProperty -Name 'Startdatum' -Value $Startdatum
$object | Add-Member -MemberType NoteProperty -Name 'Starttid' -Value $starttid
$object | Add-Member -MemberType NoteProperty -Name 'Varaktighet' -Value $mw.Duration
$object | Add-Member -MemberType NoteProperty -Name 'Deployment' -Value $collectionid.name
$resultColl += $object
}
}
if ($mw.RecurrenceType -eq 3)
{
$computername = $device.Name
#$query = "SELECT applikation FROM tblinmatning WHERE skrotad=0 AND servernamn='$Computername'"
#$data = Invoke-Sqlcmd -ServerInstance $dbserver -Database serverlista -Query $query
$Startdatum = ($mw.StartTime).ToString("yyyy-MM-dd")
$starttid = ($mw.StartTime).ToString("hh:mm")
$object = New-Object -TypeName PSObject
#$object | Add-Member -MemberType NoteProperty -Name 'Applikation' -Value $data.applikation
$object | Add-Member -MemberType NoteProperty -Name 'Server' -Value $device.name
$object | Add-Member -MemberType NoteProperty -Name 'Startdatum' -Value $Startdatum
$object | Add-Member -MemberType NoteProperty -Name 'Starttid' -Value $mw.Name
$object | Add-Member -MemberType NoteProperty -Name 'Varaktighet' -Value $mw.Duration
$object | Add-Member -MemberType NoteProperty -Name 'Deployment' -Value $collectionid.name
$resultColl += $object
}
}
}
}
}
$ResultColl | Export-Csv -Path $CSVFileSavePath -Encoding UTF8
Write-Log -LogString "$scriptname - File $CSVFileSavePath created"
$ResultColl.Count
}
else
{
Write-Log -LogString "$scriptname - Date not equal patchtuesday $checkdatestart and its now $todayshort. This report will run $ReportdayCompareShort"
Write-Log -LogString "$scriptname - Script exit!"
set-location $PSScriptRoot
exit
}
#endregion
#region Script part 2 Create the html-file to be distributed
New-HTML -TitleText "Patchfönster- Telia Cygate Region Mellan VXOPS" -FilePath $HTMLFileSavePath -ShowHTML -Online {
New-HTMLHeader {
New-HTMLSection -Invisible {
New-HTMLPanel -Invisible {
New-HTMLText -Text "Telia Cygate Region Mellan VXOPS - Patchfönster" -FontSize 35 -Color Darkblue -FontFamily Arial -Alignment center
New-HTMLHorizontalLine
}
}
}
New-HTMLSection -Invisible -Title "Maintenance Windows $filedate"{
New-HTMLTable -DataTable $ResultColl -PagingLength 35 -Style compact
}
New-HTMLFooter {
New-HTMLSection -Invisible {
New-HTMLPanel -Invisible {
New-HTMLHorizontalLine
New-HTMLText -Text "Denna lista skapades $todaydefault" -FontSize 20 -Color Darkblue -FontFamily Arial -Alignment center -FontStyle italic
}
}
}
}
#endregion
#Region CSS and HTML for mail thru Send-MailKitMessage
#endregion
#Region HTML Mail
#Variable needed in html
$collectionname = (Get-CMCollection -id $collectionidToCheck).name
$Body = @"
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Server Mainenance Windows - Telia Cygate Region Mellan VXOPS</title>
<style>
th {
font-family: Arial, Helvetica, sans-serif;
color: White;
font-size: 12px;
border: 1px solid black;
padding: 3px;
background-color: Black;
}
p {
font-family: Arial, Helvetica, sans-serif;
color: black;
font-size: 12px;
}
ol {
font-family: Arial, Helvetica, sans-serif;
list-style-type: square;
color: black;
font-size: 12px;
}
H1 {
font-family: Arial, Helvetica, sans-serif;
color: black;
font-size: 18px;
}
tr {
font-family: Arial, Helvetica, sans-serif;
color: black;
font-size: 11px;
vertical-align: text-top;
}
body {
background-color: lightgray;
}
table {
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 5px;
background-color: #E0F3F7;
}
</style>
</head>
<body>
<p><h1>Server Maintenance Windows - List</h1></p>
<p>Bifogad fil innehåller servrar från collection $collectionname.<br><br>
med fönster mellan $patchtuesdayThisMonth och $patchtuesdayNextMonth<br>
<hr>
</p>
<p>Report created $((Get-Date).ToString()) from <b><i>$($Env:Computername)</i></b></p>
</body>
</html>
"@
#endregion
#Region Mailsettings
#use secure connection if available ([bool], optional)
$UseSecureConnectionIfAvailable = $false
#authentication ([System.Management.Automation.PSCredential], optional)
$Credential = [System.Management.Automation.PSCredential]::new("Username", (ConvertTo-SecureString -String "Password" -AsPlainText -Force))
#SMTP server ([string], required)
$SMTPServer = $SMTP
#port ([int], required)
$Port = $MailPortnumber
#sender ([MimeKit.MailboxAddress] http://www.mimekit.net/docs/html/T_MimeKit_MailboxAddress.htm, required)
$From = [MimeKit.MailboxAddress]$MailFrom
#recipient list ([MimeKit.InternetAddressList] http://www.mimekit.net/docs/html/T_MimeKit_InternetAddressList.htm, required)
$RecipientList = [MimeKit.InternetAddressList]::new()
$recipientlistXML = $xml.Configuration.Recipients | ForEach-Object {$_.Recipients.Email}
foreach ($Recipient in $recipientlistXML)
{
$RecipientList.Add([MimeKit.InternetAddress]$Recipient)
}
#cc list ([MimeKit.InternetAddressList] http://www.mimekit.net/docs/html/T_MimeKit_InternetAddressList.htm, optional)
#$CCList=[MimeKit.InternetAddressList]::new()
#$CCList.Add([MimeKit.InternetAddress]$EmailToCC)
#bcc list ([MimeKit.InternetAddressList] http://www.mimekit.net/docs/html/T_MimeKit_InternetAddressList.htm, optional)
$BCCList = [MimeKit.InternetAddressList]::new()
$BCCList.Add([MimeKit.InternetAddress]"BCCRecipient1EmailAddress")
#subject ([string], required)
$Subject = [string]"Serverpatchning $MailCustomer $monthname $year"
#text body ([string], optional)
#$TextBody=[string]"TextBody"
#HTML body ([string], optional)
$HTMLBody = [string]$Body
#attachment list ([System.Collections.Generic.List[string]], optional)
$AttachmentList = [System.Collections.Generic.List[string]]::new()
$AttachmentList.Add("$HTMLFileSavePath")
$AttachmentList.Add("$CSVFileSavePath")
# Mailparameters
$Parameters = @{
"UseSecureConnectionIfAvailable" = $UseSecureConnectionIfAvailable
#"Credential"=$Credential
"SMTPServer" = $SMTPServer
"Port" = $Port
"From" = $From
"RecipientList" = $RecipientList
#"CCList"=$CCList
#"BCCList"=$BCCList
"Subject" = $Subject
#"TextBody"=$TextBody
"HTMLBody" = $HTMLBody
"AttachmentList" = $AttachmentList
}
#endregion
#Region Send Mail
Send-MailKitMessage @Parameters
Write-Log -LogString "$scriptname - Mail on it´s way to $RecipientList"
set-location $PSScriptRoot
Write-Log -LogString "$scriptname - Script exit!"
Write-MWLog -LogString "Script done!"
#endregion