forked from vCheckReport/vCheck-AD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vCheck.ps1
920 lines (794 loc) · 31.4 KB
/
vCheck.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
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
<#
.SYNOPSIS
vCheck is a PowerShell HTML framework script, designed to run as a scheduled
task before you get into the office to present you with key information via
an email directly to your inbox in a nice easily readable format.
.DESCRIPTION
vCheck Daily Report for vSphere
vCheck is a PowerShell HTML framework script, the script is designed to run
as a scheduled task before you get into the office to present you with key
information via an email directly to your inbox in a nice easily readable format.
This script picks on the key known issues and potential issues scripted as
plugins for various technologies written as powershell scripts and reports
it all in one place so all you do in the morning is check your email.
One of they key things about this report is if there is no issue in a particular
place you will not receive that section in the email, for example if there are
no datastores with less than 5% free space (configurable) then the disk space
section in the virtual infrastructure version of this script, it will not show
in the email, this ensures that you have only the information you need in front
of you when you get into the office.
This script is not to be confused with an Audit script, although the reporting
framework can also be used for auditing scripts too. I dont want to remind you
that you have 5 hosts and what there names are and how many CPUs they have each
and every day as you dont want to read that kind of information unless you need
it, this script will only tell you about problem areas with your infrastructure.
.NOTES
File Name : vCheck.ps1
Author : Alan Renouf - @alanrenouf
Version : 6.23
Thanks to all who have commented on my blog to help improve this project
all beta testers and previous contributors to this script.
.LINK
http://www.virtu-al.net/vcheck-pluginsheaders/vcheck
.LINK
https://github.com/alanrenouf/vCheck-vSphere/
.INPUTS
No inputs required
.OUTPUTS
HTML formatted email, Email with attachment, HTML File
.PARAMETER config
If this switch is set, run the setup wizard
.PARAMETER Outputpath
This parameter specifies the output location for files.
.PARAMETER job
This parameter lets you specify an xml config file for this invokation
#>
[CmdletBinding()]
param (
[Switch]$config,
[ValidateScript({ Test-Path $_ -PathType 'Container' })]
[string]$Outputpath=$Env:TEMP,
[ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
[string]$job
)
$vCheckVersion = "6.23"
$Date = Get-Date
#region Internationalization
################################################################################
# Internationalization #
################################################################################
$lang = DATA {
ConvertFrom-StringData @'
setupMsg01 =
setupMsg02 = Welcome to vCheck by Virtu-Al http://virtu-al.net
setupMsg03 = =================================================
setupMsg04 = This is the first time you have run this script or you have re-enabled the setup wizard.
setupMsg05 =
setupMsg06 = To re-run this wizard in the future please use vCheck.ps1 -Config
setupMsg07 = To get usage information, please use Get-Help vCheck.ps1
setupMsg08 =
setupMsg09 = Please complete the following questions or hit Enter to accept the current setting
setupMsg10 = After completing this wizard the vCheck report will be displayed on the screen.
setupMsg11 =
resFileWarn = Image File not found for {0}!
pluginInvalid = Plugin does not exist: {0}
pluginpathInvalid = Plugin path "{0}" is invalid, defaulting to {1}
gvInvalid = Global Variables path invalid in job specification, defaulting to {0}
varUndefined = Variable `${0} is not defined in GlobalVariables.ps1
pluginActivity = Evaluating plugins
pluginStatus = [{0} of {1}] {2}
Complete = Complete
pluginBegin = \nBegin Plugin Processing
pluginStart = ..start calculating {0} by {1} v{2} [{3} of {4}]
pluginEnd = ..finished calculating {0} by {1} v{2} [{3} of {4}]
repTime = This report took {0} minutes to run all checks, completing on {1} at {2}
repPRTitle = Plugin Report
repTTRTitle = Time to Run
slowPlugins = The following plugins took longer than {0} seconds to run, there may be a way to optimize these or remove them if not needed
emailSend = ..Sending Email
emailAtch = vCheck attached to this email
HTMLdisp = ..Displaying HTML results
'@
}
Import-LocalizedData -BaseDirectory ($ScriptPath + "\lang") -BindingVariable lang -ErrorAction SilentlyContinue
#endregion Internationalization
#region functions
################################################################################
# Functions #
################################################################################
<# Write timestamped output to screen #>
function Write-CustomOut ($Details) {
$LogDate = Get-Date -Format "HH:mm:ss"
Write-OutPut "[$($LogDate)] $Details"
}
<# Search $file_content for name/value pair with ID_Name and return value #>
Function Get-ID-String ($file_content, $ID_name) {
if ($file_content | Select-String -Pattern "\$+$ID_name\s*=") {
$value = (($file_content | Select-String -pattern "\$+${ID_name}\s*=").toString().split("=")[1]).Trim(' "')
return ($value)
}
}
<# Get basic information abount a plugin #>
Function Get-PluginID ($Filename) {
# Get the identifying information for a plugin script
$file = Get-Content $Filename
$Title = Get-ID-String $file "Title"
if (!$Title) { $Title = $Filename }
$PluginVersion = Get-ID-String $file "PluginVersion"
$Author = Get-ID-String $file "Author"
$Ver = "{0:N1}" -f $PluginVersion
return @{ "Title" = $Title; "Version" = $Ver; "Author" = $Author }
}
Function Invoke-Settings {
<#
.DESCRIPTION
Run through settings for specified file, expects question on one line, and variable/value on following line
.NOTES
Updated: 20150428
Updated By: Kevin Kirkpatrick (@vScripter - Twitter/GitHub)
Update Notes:
- Remove Write-Host in favor of Write-Warning; this was based on setting the color of Write-Host to 'warning' colors
- converted function to advanced function
- moved parameters out of function declaration and into the param declaration
- moved all code into the PROCESS block
- improved code spacing for improved readability
- added comment based help section for notes/comments
#>
[CmdletBinding(PositionalBinding = $true)]
param (
[parameter(Position = 0)]
$Filename,
[parameter(Position = 1)]
$GB
)
PROCESS {
$file = Get-Content $filename
$OriginalLine = ($file | Select-String -Pattern "# Start of Settings").LineNumber
$EndLine = ($file | Select-String -Pattern "# End of Settings").LineNumber
if (!(($OriginalLine + 1) -eq $EndLine)) {
$Array = @()
$Line = $OriginalLine
$PluginName = (Get-PluginID $Filename).Title
If ($PluginName.EndsWith(".ps1", 1)) {
$PluginName = ($PluginName.split("\")[-1]).split(".")[0]
} # end if
Write-Warning -Message "`n$PluginName"
do {
$Question = $file[$Line]
$Line++
$Split = ($file[$Line]).Split("=")
$Var = $Split[0]
$CurSet = $Split[1].Trim()
# Check if the current setting is in speech marks
$String = $false
if ($CurSet -match '"') {
$String = $true
$CurSet = $CurSet.Replace('"', '').Trim()
} # end if
$NewSet = Read-Host "$Question [$CurSet]"
If (-not $NewSet) {
$NewSet = $CurSet
} # end if
If ($String) {
$Array += $Question
$Array += "$Var= `"$NewSet`""
} Else {
$Array += $Question
$Array += "$Var= $NewSet"
} # end if/else
$Line++
} Until ($Line -ge ($EndLine - 1))
$Array += "# End of Settings"
$out = @()
$out = $File[0..($OriginalLine - 1)]
$out += $array
$out += $File[$Endline..($file.count - 1)]
if ($GB) {
$out[$SetupLine] = '$SetupWizard = $False'
} # end if
$out | Out-File $Filename
} # end if
} # end PROCESS block
} # end Function Invoke-Settings
<# Replace HTML Entities in string. Used to stop <br /> tags from being mangled in tables #>
function Format-HTMLEntities {
param ([string]$content)
$replace = @{
"<" = "<";
">" = ">";
}
foreach ($r in $replace.Keys.GetEnumerator()) {
$content = $content -replace $r, $replace[$r]
}
return $content
}
<# Takes an array of content, and optional formatRules and generated HTML table #>
Function Get-HTMLTable {
param ($Content, $FormatRules)
# Use an XML object for ease of use
$XMLTable = [xml]($content | ConvertTo-Html -Fragment)
$XMLTable.table.SetAttribute("width", "100%")
# If only one column, fix up the table header
if (($content | Get-Member -MemberType Properties).count -eq 1)
{
$XMLTable.table.tr[0].th = (($content | Get-Member -MemberType Properties) | Select -ExpandProperty Name -First 1).ToString()
}
# If format rules are specified
if ($FormatRules) {
# Check each cell to see if there are any format rules
for ($RowN = 1; $RowN -lt $XMLTable.table.tr.count; $RowN++) {
for ($ColN = 0; $ColN -lt $XMLTable.table.tr[$RowN].td.count; $ColN++) {
if ($FormatRules.keys -contains $XMLTable.table.tr[0].th[$ColN]) {
# Current cell has a rule, test to see if they are valid
foreach ($rule in $FormatRules[$XMLTable.table.tr[0].th[$ColN]]) {
if ($XMLTable.table.tr[$RowN].td[$ColN]."#text")
{
$value = $XMLTable.table.tr[$RowN].td[$ColN]."#text"
}
else
{
$value = $XMLTable.table.tr[$RowN].td[$ColN]
}
if ($value -notmatch "^[0-9.]+$") {
$value = """$value"""
}
if (Invoke-Expression ("{0} {1}" -f $value, [string]$rule.Keys)) {
# Find what to
$RuleScope = ([string]$rule.Values).split(",")[0]
$RuleActions = ([string]$rule.Values).split(",")[1].split("|")
switch ($RuleScope) {
"Row" {
for ($TRColN = 0; $TRColN -lt $XMLTable.table.tr[$RowN].td.count; $TRColN++) {
$XMLTable.table.tr[$RowN].selectSingleNode("td[$($TRColN + 1)]").SetAttribute($RuleActions[0], $RuleActions[1])
}
}
"Cell" {
if ($RuleActions[0] -eq "cid") {
# Do Image - create new XML node for img and clear #text
$XMLTable.table.tr[$RowN].selectSingleNode("td[$($ColN + 1)]")."#text" = ""
$elem = $XMLTable.CreateElement("img")
$elem.SetAttribute("src", ("cid:{0}" -f $RuleActions[1]))
# Add img size if specified
if ($RuleActions[2] -match "(\d+)x(\d+)") {
$elem.SetAttribute("width", $Matches[1])
$elem.SetAttribute("height", $Matches[2])
}
$XMLTable.table.tr[$RowN].selectSingleNode("td[$($ColN + 1)]").AppendChild($elem) | Out-Null
# Increment usage counter (so we don't have .bin attachments)
Set-ReportResource $RuleActions[1]
} else {
$XMLTable.table.tr[$RowN].selectSingleNode("td[$($ColN + 1)]").SetAttribute($RuleActions[0], $RuleActions[1])
}
}
}
}
}
}
}
}
}
return (Format-HTMLEntities ([string]($XMLTable.OuterXml)))
}
<# Takes an array of content, and returns HTML table with header column #>
Function Get-HTMLList {
param ([array]$content)
if ($content.count -gt 0) {
# Create XML doc from HTML. Remove colgroup and header row
if ($content.count -gt 1) {
[xml]$XMLTable = $content | ConvertTo-HTML -Fragment
$XMLTable.table.RemoveChild($XMLTable.table.colgroup) | out-null
$XMLTable.table.RemoveChild($XMLTable.table.tr[0]) | out-null
$XMLTable.table.SetAttribute("width", "100%")
} else {
[xml]$XMLTable = $content | ConvertTo-HTML -Fragment -As List
}
# Replace the first column td with th
for ($i = 0; $i -lt $XMLTable.table.tr.count; $i++) {
$node = $XMLTable.table.tr[$i].SelectSingleNode("/table/tr[$($i + 1)]/td[1]")
$elem = $XMLTable.CreateElement("th")
$elem.InnerText = $node."#text"
$trNode = $XMLTable.SelectSingleNode("/table/tr[$($i + 1)]")
$trNode.ReplaceChild($elem, $node) | Out-Null
}
# If only one column, fix up the table header
if (($content | Get-Member -MemberType Properties).count -eq 1)
{
$XMLTable.table.tr[0].th = (($content | Get-Member -MemberType Properties) | Select -ExpandProperty Name -First 1).ToString()
}
return (Format-HTMLEntities ([string]($XMLTable.OuterXml)))
}
}
<# Returns HTML fragment for chart. Calls Get-ChartResource to generate chart image #>
function Get-HTMLChart {
param (
[string]$cidbase,
[Object[]]$ChartObjs
)
$html = ""
$i = 0
foreach ($ChartObj in $ChartObjs) {
$i++
$base64 = Get-ChartResource $ChartObj
$cid = $cidbase + "-" + $i
Add-ReportResource -cid $cid -ResourceData $Base64 -Type "Base64" -Used $true
$html += "<img src='cid:$cid' />"
}
return $html
}
<# Create a new Chert object, this will get fed back down the output stream as part
of plugin processing. This allows us to keep the same interface for plugins content #>
function New-Chart {
param (
[int]$height,
[int]$width,
[Parameter(Mandatory = $true)]
[Hashtable[]]$data,
[string]$title,
[string]$titleX,
[string]$titleY,
[ValidateSet("Area", "Bar", "BoxPlot", "Bubble", "Candlestick", "Column", "Doughnut", "ErrorBar", "FastLine",
"FastPoint", "Funnel", "Kagi", "Line", "Pie", "Point", "PointAndFigure", "Polar", "Pyramid",
"Radar", "Range", "RangeBar", "RangeColumn", "Renko", "Spline", "SplineArea", "SplineRange",
"StackedArea", "StackedArea100", "StackedBar", "StackedBar100", "StackedColumn",
"StackedColumn100", "StepLine", "Stock", "ThreeLineBreak")]
$ChartType = "bar"
)
# If chartsize is specified in style, use it unless explicitly set
if ($ChartSize -and (-not $height -and -not $width)) {
if ($ChartSize -match "(\d+)x(\d+)") {
$height = $Matches[1]
$width = $Matches[2]
}
}
# if size not set in style or function call, default to 400x400 (maybe make this a globalVariable?)
if (-not $ChartSize -and (-not $height -and -not $width)) {
$height = 400
$width = 400
}
return New-Object PSObject -Property @{
"height" = $height;
"width" = $width;
"data" = $data;
"title" = $title;
"titleX" = $titleX;
"titleY" = $titleY;
"ChartType" = $ChartType
}
}
<# Creates a chart Image #>
function Get-ChartResource {
param (
$ChartDef
)
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization")
# Create a new chart object
$Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart
$Chart.Width = $ChartDef.width
$Chart.Height = $ChartDef.height
$Chart.AntiAliasing = "All"
# Create a chartarea to draw on and add to chart
$ChartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea
$Chart.ChartAreas.Add($ChartArea)
# Set title and axis labels
if ($ChartDef.title) {
$titleRef = $Chart.Titles.Add($ChartDef.title)
}
if ($ChartDef.titleX) {
$ChartArea.AxisX.Title = $ChartDef.titleX
}
if ($ChartDef.titleY) {
$ChartArea.AxisY.Title = $ChartDef.titleY
}
# change chart colours
if ($ChartBackground) {
$Chart.BackColor = Get-ChartColours $ChartBackground
$ChartArea.BackColor = Get-ChartColours $ChartBackground
} else {
$Chart.BackColor = [System.Drawing.Color]::Transparent
$ChartArea.BackColor = [System.Drawing.Color]::Transparent
}
# If we have style
if ($ChartColours) {
$Chart.PaletteCustomColors = Get-ChartColours $ChartColours
$Chart.Palette = [System.Windows.Forms.DataVisualization.Charting.ChartColorPalette]::None
}
if ($ChartFontColour) {
$Chart.ForeColor = Get-ChartColours $ChartFontColour
}
# Add data to chart and set chart type
for ($i = 0; $i -lt $ChartDef.data.count; $i++) {
[void]$Chart.Series.Add("Data$i")
$Chart.Series["Data$i"].Points.DataBindXY($ChartDef.data[$i].Keys, $ChartDef.data[$i].Values)
$Chart.Series["Data$i"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::($ChartDef.ChartType)
}
# Do some funky work to increase the DPI so charts look nice. Default 96 DPI looks terrible :(
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$bmp = New-Object System.Drawing.Bitmap(($ChartDef.width), ($ChartDef.height))
$bmp.SetResolution(384, 384);
if ($ChartArea.BackColor -eq [System.Drawing.Color]::Transparent) {
$bmp.MakeTransparent()
}
$chart.DrawToBitmap($bmp, (new-object System.Drawing.Rectangle(0, 0, $ChartDef.width, $ChartDef.height)))
$ms = new-Object IO.MemoryStream
$bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png);
$ms.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
$byte = New-Object byte[] $ms.Length
$ms.read($byte, 0, $ms.length) | Out-Null
return ("png|{0}" -f [System.Convert]::ToBase64String($byte))
}
<# Takes Array of HTML colour codes and returns Color object #>
function Get-ChartColours {
param (
[string[]]$ChartColours
)
foreach ($colour in $ChartColours) {
[System.Drawing.Color]::FromArgb([Convert]::ToInt32($colour.Substring(0, 2), 16),
[Convert]::ToInt32($colour.Substring(2, 2), 16),
[Convert]::ToInt32($colour.Substring(4, 2), 16));
}
}
<# Adds a resource to the resource array, to be included in report.
At the moment, only "File" types are supported- this will be expanded to include
SystemIcons and raw byte data (so images can be packaged completely in styles if desired
#>
function Add-ReportResource {
param (
$cid,
$ResourceData,
[ValidateSet("File", "SystemIcons", "Base64")]
$Type = "File",
$Used = $false
)
# If cid does not exist, add it
if ($global:ReportResources.Keys -notcontains $cid) {
$global:ReportResources.Add($cid, @{
"Data" = ("{0}|{1}" -f $Type, $ResourceData);
"Uses" = 0
})
}
# Update uses count if $Used set (Should normally be incremented with Set-ReportResource)
# Useful for things like headers where they are always required.
if ($Used) {
($global:ReportResources[$cid].Uses)++
}
}
Function Set-ReportResource {
param (
$cid
)
# Increment use
($global:ReportResources[$cid].Uses)++
}
<# Gets a resource in the specified ReturnType (eventually support both a
base64 encoded string, and Linked Resource for email #>
function Get-ReportResource {
param (
$cid,
[ValidateSet("embed", "linkedresource")]
$ReturnType = "embed"
)
$data = $global:ReportResources[$cid].Data.Split("|")
# Process each resource type differently
switch ($data[0]) {
"File" {
# Check the path exists
if (Test-Path $data[1] -ErrorAction SilentlyContinue) {
if ($ReturnType -eq "embed") {
# return a MIME/Base64 combo for embedding in HTML
$imgData = Get-Content ($data[1]) -Encoding Byte
$type = $data[1].substring($data[1].LastIndexOf(".") + 1)
return ("data:image/{0};base64,{1}" -f $type, [System.Convert]::ToBase64String($imgData))
}
if ($ReturnType -eq "linkedresource") {
# return a linked resource to be added to mail message
$lr = New-Object system.net.mail.LinkedResource($data[1])
$lr.ContentId = $cid
return $lr;
}
} else {
Write-Warning ($lang.resFileWarn -f $cid)
}
}
"SystemIcons" {
# Take the SystemIcon Name - see http://msdn.microsoft.com/en-us/library/system.drawing.systemicons(v=vs.110).aspx
# Load the image into a MemoryStream in PNG format (to preserve transparency)
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$bmp = ([System.Drawing.SystemIcons]::($data[1])).toBitmap()
$bmp.MakeTransparent()
$ms = new-Object IO.MemoryStream
$bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::PNG)
$ms.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
if ($ReturnType -eq "embed") {
# return a MIME/Base64 combo for embedding in HTML
$byte = New-Object byte[] $ms.Length
$ms.read($byte, 0, $ms.length) | Out-Null
return ("data:image/png;base64," + [System.Convert]::ToBase64String($byte))
}
if ($ReturnType -eq "linkedresource") {
# return a linked resource to be added to mail message
$lr = New-Object system.net.mail.LinkedResource($ms)
$lr.ContentId = $cid
return $lr;
}
}
"Base64" {
if ($ReturnType -eq "embed") {
return ("data:image/{0};base64,{1}" -f $data[1], $data[2])
}
if ($ReturnType -eq "linkedresource") {
$w = [system.convert]::FromBase64String($data[2])
$ms = new-Object IO.MemoryStream
$ms.Write($w, 0, $w.Length);
$ms.Seek(0, [System.IO.SeekOrigin]::Begin) | Out-Null
$lr = New-Object system.net.mail.LinkedResource($ms)
$lr.ContentId = $cid
return $lr;
}
}
}
}
#endregion functions
#region initialization
################################################################################
# Initialization #
################################################################################
# Setup all paths required for script to run
$ScriptPath = (Split-Path ((Get-Variable MyInvocation).Value).MyCommand.Path)
$PluginsFolder = $ScriptPath + "\Plugins\"
# if we have the job parameter set, get the paths from the config file.
if ($job) {
[xml]$jobConfig = Get-Content $job
# Use GlobalVariables path if it is valid, otherwise use default
if (Test-Path $jobConfig.vCheck.globalVariables) {
$GlobalVariables = (Get-Item $jobConfig.vCheck.globalVariables).FullName
} else {
$GlobalVariables = $ScriptPath + "\GlobalVariables.ps1"
Write-Warning ($lang.gvInvalid -f $GlobalVariables)
}
# Get Plugin paths
$PluginPaths = @()
if ($jobConfig.vCheck.plugins.path) {
foreach ($PluginPath in ($jobConfig.vCheck.plugins.path -split ";")) {
if (Test-Path $PluginPath) {
$PluginPaths += (Get-Item $PluginPath).Fullname
$PluginPaths += Get-Childitem $PluginPath -Recurse | ?{ $_.PSIsContainer } | Select -ExpandProperty FullName
} else {
$PluginPaths += $ScriptPath + "\Plugins"
Write-Warning ($lang.pluginpathInvalid -f $PluginPath, ($ScriptPath + "\Plugins"))
}
}
$PluginPaths = $PluginPaths | Sort-Object -unique
# Get all plugins and test they are correct
$vCheckPlugins = @()
if ($jobConfig.vCheck.plugins.plugin)
{
foreach ($plugin in $jobConfig.vCheck.plugins.plugin) {
$testedPaths = 0
foreach ($PluginPath in $PluginPaths) {
$testedPaths++
if (Test-Path ("{0}\{1}" -f $PluginPath, $plugin)) {
$vCheckPlugins += Get-Item ("{0}\{1}" -f $PluginPath, $plugin)
break;
}
# Plugin not found in any search path
elseif ($testedPaths -eq $PluginPaths.Count) {
Write-Warning ($lang.pluginInvalid -f $plugin)
}
}
}
}
else
{
# Just a path specified, use all plugins
$vCheckPlugins = Get-ChildItem $PluginPaths -Filter *.ps1
}
}
# if no valid plugins specified, fall back to default
if (!$vCheckPlugins) {
$vCheckPlugins = Get-ChildItem -Path $PluginsFolder -filter "*.ps1" -Recurse | Sort FullName
}
} else {
$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }
$vCheckPlugins = @(Get-ChildItem -Path $PluginsFolder -filter "*.ps1" -Recurse | where { $_.Directory -match "initialize" } | Sort $ToNatural)
$PluginsSubFolder = Get-ChildItem -Path $PluginsFolder | where { ($_.PSIsContainer) -and ($_.Name -notmatch "initialize") -and ($_.Name -notmatch "finish") }
$vCheckPlugins += $PluginsSubFolder | % { Get-ChildItem -Path $_.FullName -filter "*.ps1" | Sort $ToNatural }
$vCheckPlugins += Get-ChildItem -Path $PluginsFolder -filter "*.ps1" -Recurse | where { $_.Directory -match "finish" } | Sort $ToNatural
$GlobalVariables = $ScriptPath + "\GlobalVariables.ps1"
}
## Determine if the setup wizard needs to run
$file = Get-Content $GlobalVariables
$Setup = ($file | Select-String -Pattern '# Set the following to true to enable the setup wizard for first time run').LineNumber
$SetupLine = $Setup++
$SetupSetting = Invoke-Expression (($file[$SetupLine]).Split("="))[1]
if ($SetupSetting -or $config) {
Clear-Host
($lang.GetEnumerator() | Where-Object { $_.Name -match "setupMsg[0-9]*" } | Sort-Object Name) | ForEach-Object {
Write-Warning -Message "$($_.value)"
}
Invoke-Settings -Filename $GlobalVariables -GB $true
Foreach ($plugin in $vCheckPlugins) {
Invoke-Settings -Filename $plugin.Fullname
}
}
## Include GlobalVariables and validate settings (at the moment just check they exist)
. $GlobalVariables
$vcvars = @("SetupWizard", "reportHeader", "SMTPSRV", "EmailFrom", "EmailTo", "EmailSubject", "DisplaytoScreen", "SendEmail", "SendAttachment", "TimeToRun", "PluginSeconds", "Style", "Date")
foreach ($vcvar in $vcvars) {
if (!($(Get-Variable -Name "$vcvar" -Erroraction 'SilentlyContinue'))) {
Write-Error ($lang.varUndefined -f $vcvar)
}
}
# Create empty array of resources (i.e. Images)
$global:ReportResources = @{ }
## Set the StylePath and include it
$StylePath = $ScriptPath + "\Styles\" + $Style
if (!(Test-Path ($StylePath))) {
# The path is not valid
# Use the default style
Write-Warning "Style path ($($StylePath)) is not valid"
$StylePath = $ScriptPath + "\Styles\VMware"
Write-Warning "Using $($StylePath)"
}
# Import the Style
. ("$($StylePath)\Style.ps1")
#endregion initialization
#region scriptlogic
################################################################################
# Script logic #
################################################################################
# Start generating the report
$PluginResult = @()
Write-Warning -Message $lang.pluginBegin
# Loop over all enabled plugins
$p = 0
$vCheckPlugins | Foreach {
$TableFormat = $null
$PluginInfo = Get-PluginID $_.Fullname
$p++
Write-CustomOut ($lang.pluginStart -f $PluginInfo["Title"], $PluginInfo["Author"], $PluginInfo["Version"], $p, $vCheckPlugins.count)
$pluginStatus = ($lang.pluginStatus -f $p, $vCheckPlugins.count, $_.Name)
Write-Progress -ID 1 -Activity $lang.pluginActivity -Status $pluginStatus -PercentComplete (100 * $p/($vCheckPlugins.count))
$TTR = [math]::round((Measure-Command { $Details = @(. $_.FullName)}).TotalSeconds, 2)
Write-CustomOut ($lang.pluginEnd -f $PluginInfo["Title"], $PluginInfo["Author"], $PluginInfo["Version"], $p, $vCheckPlugins.count)
# Do a replacement for [count] for number of items returned in $header
$Header = $Header -replace "\[count\]", $Details.count
$PluginResult += New-Object PSObject -Property @{
"Title" = $Title;
"Author" = $PluginInfo["Author"];
"Version" = $PluginInfo["Version"];
"Details" = $Details;
"Display" = $Display;
"TableFormat" = $TableFormat;
"Header" = $Header;
"Comments" = $Comments;
"TimeToRun" = $TTR;
}
}
Write-Progress -ID 1 -Activity $lang.pluginActivity -Status $lang.Complete -Completed
# Add report on plugins
if ($reportOnPlugins) {
$Comments = "Plugins in numerical order"
$Plugins = @()
foreach ($Plugin in (Get-ChildItem $PluginsFolder -Include *.ps1, *.ps1.disabled -Recurse)) {
$Plugins += New-Object PSObject -Property @{
"Name" = (Get-PluginID $Plugin.FullName).Title;
"Enabled" = (($vCheckPlugins | Select -ExpandProperty FullName) -Contains $plugin.FullName)
}
}
if ($ListEnabledPluginsFirst) {
$Plugins = $Plugins | Sort -property @{ Expression = "Enabled"; Descending = $true }
$Comments = "Plugins in numerical order, enabled plugins listed first"
}
$PluginResult += New-Object PSObject -Property @{
"Title" = $lang.repPRTitle;
"Author" = "vCheck";
"Version" = $vCheckVersion;
"Details" = $Plugins;
"Display" = "Table";
"TableFormat" = $null;
"Header" = $lang.repPRTitle;
"Comments" = $Comments;
"TimeToRun" = 0;
}
}
# Add Time to Run detail for plugins - if specified in GlobalVariables.ps1
if ($TimeToRun) {
$Finished = Get-Date
$PluginResult += New-Object PSObject -Property @{
"Title" = $lang.repTTRTitle;
"Author" = "vCheck";
"Version" = $vCheckVersion;
"Details" = ($PluginResult | Where { $_.TimeToRun -gt $PluginSeconds } | Select Title, TimeToRun | Sort-Object TimeToRun -Descending);
"Display" = "List";
"TableFormat" = $null;
"Header" = ($lang.repTime -f [math]::round(($Finished - $Date).TotalMinutes, 2), ($Finished.ToLongDateString()), ($Finished.ToLongTimeString()));
"Comments" = ($lang.slowPlugins -f $PluginSeconds);
"TimeToRun" = 0;
}
}
#endregion scriptlogic
#region output
################################################################################
# Output #
################################################################################
# Loop over plugin results and generate HTML from style
$emptyReport = $true
$p = 1
Foreach ($pr in $PluginResult) {
If ($pr.Details) {
$emptyReport = $false
switch ($pr.Display) {
"List" { $pr.Details = Get-HTMLList $pr.Details }
"Table" { $pr.Details = Get-HTMLTable $pr.Details $pr.TableFormat }
"Chart" { $pr.Details = Get-HTMLChart "plugin$($p)" $pr.Details }
default { $pr.Details = $null }
}
$pr | Add-Member -Type NoteProperty -Name pluginID -Value "plugin-$p"
$p++
}
}
# Run Style replacement
$MyReport = Get-ReportHTML
# Set the output filename
if (-not (Test-Path -PathType Container $Outputpath)) { New-Item $Outputpath -type directory | Out-Null }
$Filename = ("{0}\{1}_vCheck_{2}.htm" -f $Outputpath, $Server, (Get-Date -Format "yyyyMMdd_HHmm"))
# Always generate the report with embedded images
$embedReport = $MyReport
# Loop over all CIDs and replace them
Foreach ($cid in $global:ReportResources.Keys) {
$embedReport = $embedReport -replace ("cid:{0}" -f $cid), (Get-ReportResource $cid -ReturnType "embed")
}
$embedReport | Out-File -encoding ASCII -filepath $Filename
# Display to screen
if ($DisplayToScreen -and (!($emptyReport -and !$DisplayReportEvenIfEmpty))) {
Write-CustomOut $lang.HTMLdisp
Invoke-Item $Filename
}
# Generate email
if ($SendEmail -and (!($emptyReport -and !$EmailReportEvenIfEmpty))) {
Write-CustomOut $lang.emailSend
$msg = New-Object System.Net.Mail.MailMessage ($EmailFrom, $EmailTo)
# If CC address specified, add
If ($EmailCc -ne "") {
$msg.CC.Add($EmailCc)
}
$msg.subject = $EmailSubject
# if send attachment, just send plaintext email with HTML report attached
If ($SendAttachment) {
$msg.Body = $lang.emailAtch
$attachment = new-object System.Net.Mail.Attachment $Filename
$msg.Attachments.Add($attachment)
}
# Otherwise send the HTML email
else {
$msg.IsBodyHtml = $true;
$html = [System.Net.Mail.AlternateView]::CreateAlternateViewFromString($MyReport, $null, 'text/html')
$msg.AlternateViews.Add($html)
# Loop over all CIDs and replace them
Foreach ($cid in $global:ReportResources.Keys) {
if ($global:ReportResources[$cid].Uses -gt 0) {
$lr = (Get-ReportResource $cid -ReturnType "linkedresource")
$html.LinkedResources.Add($lr);
}
}
}
# Send the email
$smtpClient = New-Object System.Net.Mail.SmtpClient
# Find the VI Server and port from the global settings file
$smtpClient.Host = ($SMTPSRV -Split ":")[0]
if (($SMTPSRV -split ":")[1]) {
$smtpClient.Port = ($SMTPSRV -split ":")[1]
}
if ($EmailSSL -eq $true) {
$smtpClient.EnableSsl = $true
}
$smtpClient.UseDefaultCredentials = $true;
$smtpClient.Send($msg)
If ($SendAttachment) { $attachment.Dispose() }
$msg.Dispose()
}
# Run EndScript once everything else is complete
if (Test-Path ($ScriptPath + "\EndScript.ps1")) {
. ($ScriptPath + "\EndScript.ps1")
}
#endregion output