-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvcheck.ps1
More file actions
1577 lines (1442 loc) · 64.6 KB
/
vcheck.ps1
File metadata and controls
1577 lines (1442 loc) · 64.6 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
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
param( [string] $VISRV)
###############################
# vCheck - Daily Error Report #
###############################
# Thanks to all who have commented on my blog to help improve this project
# Especially - Thanks to Raphaël SCHITZ (http://www.hypervisor.fr/) for his contributions and time
# And also thanks to the many vExperts who have added suggestions for this report.
#
$Version = "5.0"
#
# Changes:
# Version 5.0 - Changed the order and a few titles etc, tidy up !
# Version 4.9 - Added Inacessable VMs
# Version 4.8 - Added HA VM restarts and resets
# Version 4.7 - VMTools Issues
# Version 4.6 - Added VCB Garbage
# Version 4.5 - Added Host config issues
# Version 4.4 - Added Disk Overcommit check
# Version 4.3 - Added vSwitch free ports check
# Version 4.2 - Added General Capacity Information based on CPU and MEM ussage per cluster
# Version 4.1 - Added the ability to change the colours of the report.
# Version 4.0 - HTML Tidy up, comments added for each item and the ability to enable/disable comments.
# Version 3.9 - Adjusted log checking to include ESXi Logs
# Version 3.8 - Added ESXi check for unsupported mode enabled
# Version 3.7 - Added ESXi check for Lockdown Mode Enabled
# Version 3.6 - Added VM Memory Swap and Ballooning
# Version 3.5 - Added Host Overcommit check
# Version 3.4 - Added Guest Disk check for space (MB)
# Version 3.3 - Added Size of snapshots
# Version 3.2 - Fixed Slot size information issue
# Version 3.1 - Added VMs with High CPU Usage
# Version 3.0 - Added VMs in mis-matched Folder names
# Version 2.9 - Added counts to each titlebar and output to screen whilst running for interactive mode
# Version 2.8 - Changed VC Services to show only unexpected status
# Version 2.7 - Added VMs with outdated Hardware - vSphere Only
# Version 2.6 - Added Slot size check - vSphere Only
# version 2.5 - Added report on Hosts in a HA cluster where the swapfile location is set, check the hosts
# Version 2.4 - Added VM/Host/Cluster Alerts
# Version 2.3 - Added VMs with over x amount of vCPUs
# Version 2.2 - Added Dead SCSILuns
# Version 2.1 - Now checks for VMs stored on storage available to only one host rather than local storage
# Version 2.0 - CPU Ready
# Version 1.17 - vmkernel host log file check for warnings
# Version 1.16 - NTP Server and service check
# Version 1.15 - DRSMigrations & Local Stored VMs
# Version 1.14 - Active/Inactive VMs
# Version 1.13 - Bug Fixes
# Version 1.12 - Added Hosts in Maintenance Mode and not responding + Bug Fixes
# Version 1.11 - Simplified mail function.
# Version 1.10 - Added How many days old the snapshots are
# Version 1.9 - Added ability to change user account which makes the WMI calls
# Version 1.8 - Added Real name resolution via AD and sorted disk space by PerfFree
# Version 1.7 - Added Event Logs for VMware warnings and errors for past day
# Version 1.6 - Add details to service state to see if it is expected or not
# Version 1.5 - Check for objects to see if they exist before sending the email + add VMs with No VMTools
# You can change the following defaults by altering the below settings:
#
# Set the SMTP Server address
$SMTPSRV = "mysmtpserver.mydomain.local"
# Set the Email address to recieve from
$EmailFrom = "[email protected]"
# Set the Email address to send the email to
$EmailTo = "[email protected]"
# Use the following item to define if the output should be displayed in the local browser once completed
$DisplaytoScreen = $true
# Use the following item to define if an email report should be sent once completed
$SendEmail = $false
# Use the following area to define the colours of the report
$Colour1 = "CC0000" # Main Title - currently red
$Colour2 = "7BA7C7" # Secondary Title - currently blue
#### Detail Settings ####
# Set the username of the account with permissions to access the VI Server
# for event logs and service details - you will be asked for the same username and password
# only the first time this runs after setting the below username.
# If it is left blank it will use the credentials of the user who runs the script
$SetUsername = "bnweb\sstent"
# Set the location to store the credentials in a secure manner
$CredFile = ".\mycred.crd"
# Set if you would like to see the helpfull comments about areas of the checks
$Comments = $true
# Set the warning threshold for Datastore % Free Space
$DatastoreSpace = "5"
# Set the warning threshold for snapshots in days old
$SnapshotAge = 14
# Set the number of days to show VMs created & removed for
$VMsNewRemovedAge = 5
# Set the number of days of VC Events to check for errors
$VCEventAge = 1
# Set the number of days of VC Event Logs to check for warnings and errors
$VCEvntlgAge = 1
# Set the number of days of DRS Migrations to report and count on
$DRSMigrateAge = 1
# Local Stored VMs, do not report on any VMs who are defined below
$LVMDoNotInclude = "Template_*|VDI*"
# VMs with CD/Floppy drives not to report on
$CDFloppyConnectedOK = "APP*"
# The NTP server to check
$ntpserver = "pool.ntp.org"
# vmkernel log file checks - set the number of days to check before today
$vmkernelchk = 1
# CPU ready on VMs - To learn more read here: http://communities.vmware.com/docs/DOC-7390
$PercCPUReady = 10.0
# Change the next line to the maximum amount of vCPUs your VMs are allowed
$vCpu = 2
# Number of slots available in a cluster
$numslots = 10
# VM Cpu above x for the last x days
$CPUValue = 75
$CPUDays = 2
# VM Disk space left, set the amount you would like to report on
$MBFree = 10
# Max number of VMs per Datastore
$NumVMsPerDatastore = 5
# HA VM reset day(s) number
$HAVMresetold = 1
# HA VM restart day(s) number
$HAVMrestartold = 1
# VMHost/VMFS quota
$VMHostVMFSQuota = 28
# Datastore OverAllocation %
$OverAllocation = 100
# vSwitch Port Left
$vSwitchLeft = 5
# This section can be used to turn off certain areas of the report which may not be relevent to your installation
# Set them to $False if you do not want them in your output.
# General Summary Info
$ShowGenSum = $true
# Snapshot Information
$ShowSnap = $false
# Datastore Information
$Showdata = $false
# Hosts in Maintenance mode
$ShowMaint = $true
# Hosts not responding or Disconnected
$ShowResDis = $false
# Dead LunPath
$ShowLunPath = $flase
# VMs Created or cloned
$ShowCreated = $true
# VMs vCPU
$Showvcpu = $true
# VMs Removed
$ShowRemoved = $true
# Host Swapfile datastores
$ShowSwapFile = $false
# DRS Migrations
$ShowDRSMig = $false
# Cluster Slot Sizes
$ShowSlot = $false
# VM Hardware Version
$ShowHWVer = $true
# VI Events
$ShowVIevents = $False
# VMs in inconsistent folders
$ShowFolders = $false
# VM Tools
$Showtools = $true
# Connected CDRoms
$ShowCDRom = $false
# ConnectedFloppy Drives
$ShowFloppy = $false
# NTP Issues
$ShowNTP = $false
# Single storage VMs
$ShowSingle = $true
# VM CPU Ready
$ShowCPURDY = $true
# Host Alarms
$ShowHostAlarm = $false
# VM Alarms
$ShowVMAlarm = $false
# Cluster Alarms
$ShowCLUAlarm = $false
# VC Service Details
$ShowVCDetails = $false
# VC Event Log Errors
$ShowVCError = $false
# VC Event Log Warnings
$ShowVCWarn = $false
# VMKernel Warning entries
$ShowVMKernel = $false
# Show VM CPU Usage
$ShowVMCPU = $false
# Show ESXi Tech Support mode
$ShowTech = $false
# Show ESXi Hosts which do not have lockdown mode enabled
$Lockdown = $false
# Show VMs disk space check
$ShowGuestDisk = $false
# Show Number of VMs per Datastore
$ShowNumVMperDS = $false
# Show Overcommit
$ShowOvercommit = $true
# Show Ballooning and Swapping for VMs
$ShowSwapBal = $false
# HA VM reset log
$HAVMreset = $false
# HA VM restart log
$HAVMrestart = $false
# Host ConfigIssue
$ShowHostCIAlarm = $false
# Map Disk Region Events (http://kb.vmware.com/kb/1007331)
$ShowMapDiskRegionEvents =$false
# Capacity Info
$ShowCapacityInfo = $true
# VMHost/VMFS Quota
$VMHostVMFS = $false
# Check inaccessible or invalid VM
$ShowBlindedVM = $true
# Check VMTools Issues
$ShowtoolsIssues = $true
# Check vSwitch Port Left
$vSwitchCheck = $false
#######################################
# Start of script
# Turn off Errors
$ErrorActionPreference = "silentlycontinue"
if ($VISRV -eq ""){
Write-Host
Write-Host "Please specify a VI Server name eg...."
Write-Host " powershell.exe vCheck.ps1 MyvCenter"
Write-Host
Write-Host
exit
}
function Write-CustomOut ($Details){
$LogDate = Get-Date -Format T
Write-Host "$($LogDate) $Details"
}
function Send-SMTPmail($to, $from, $subject, $smtpserver, $body) {
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)
}
Function Get-CustomHTML ($Header){
$Report = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>$($Header)</title>
<META http-equiv=Content-Type content='text/html; charset=windows-1252'>
<style type="text/css">
TABLE {
TABLE-LAYOUT: fixed;
FONT-SIZE: 100%;
WIDTH: 100%
}
*
{
margin:0
}
.dspcont {
BORDER-RIGHT: #bbbbbb 1px solid;
BORDER-TOP: #bbbbbb 1px solid;
PADDING-LEFT: 0px;
FONT-SIZE: 8pt;
MARGIN-BOTTOM: -1px;
PADDING-BOTTOM: 5px;
MARGIN-LEFT: 0px;
BORDER-LEFT: #bbbbbb 1px solid;
WIDTH: 95%;
COLOR: #000000;
MARGIN-RIGHT: 0px;
PADDING-TOP: 4px;
BORDER-BOTTOM: #bbbbbb 1px solid;
FONT-FAMILY: Tahoma;
POSITION: relative;
BACKGROUND-COLOR: #f9f9f9
}
.filler {
BORDER-RIGHT: medium none;
BORDER-TOP: medium none;
DISPLAY: block;
BACKGROUND: none transparent scroll repeat 0% 0%;
MARGIN-BOTTOM: -1px;
FONT: 100%/8px Tahoma;
MARGIN-LEFT: 43px;
BORDER-LEFT: medium none;
COLOR: #ffffff;
MARGIN-RIGHT: 0px;
PADDING-TOP: 4px;
BORDER-BOTTOM: medium none;
POSITION: relative
}
.pageholder {
margin: 0px auto;
}
.dsp
{
BORDER-RIGHT: #bbbbbb 1px solid;
PADDING-RIGHT: 0px;
BORDER-TOP: #bbbbbb 1px solid;
DISPLAY: block;
PADDING-LEFT: 0px;
FONT-WEIGHT: bold;
FONT-SIZE: 8pt;
MARGIN-BOTTOM: -1px;
MARGIN-LEFT: 0px;
BORDER-LEFT: #bbbbbb 1px solid;
COLOR: #FFFFFF;
MARGIN-RIGHT: 0px;
PADDING-TOP: 4px;
BORDER-BOTTOM: #bbbbbb 1px solid;
FONT-FAMILY: Tahoma;
POSITION: relative;
HEIGHT: 2.25em;
WIDTH: 95%;
TEXT-INDENT: 10px;
}
.dsphead0 {
BACKGROUND-COLOR: #$($Colour1);
}
.dsphead1 {
BACKGROUND-COLOR: #$($Colour2);
}
.dspcomments {
BACKGROUND-COLOR:#FFFFE1;
COLOR: #000000;
FONT-STYLE: ITALIC;
FONT-WEIGHT: normal;
FONT-SIZE: 8pt;
}
td {
VERTICAL-ALIGN: TOP;
FONT-FAMILY: Tahoma
}
th {
VERTICAL-ALIGN: TOP;
COLOR: #$($Colour1);
TEXT-ALIGN: left
}
BODY {
margin-left: 4pt;
margin-right: 4pt;
margin-top: 6pt;
}
.MainTitle {
font-family:Arial, Helvetica, sans-serif;
font-size:20px;
font-weight:bolder;
}
.SubTitle {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
font-weight:bold;
}
.Created {
font-family:Arial, Helvetica, sans-serif;
font-size:10px;
font-weight:normal;
margin-top: 20px;
margin-bottom:5px;
}
.links { font:Arial, Helvetica, sans-serif;
font-size:10px;
FONT-STYLE: ITALIC;
}
</style>
</head>
<body>
<div class="MainTitle">$($Header)</div>
<hr size="8" color="#$($Colour1)">
<div class="SubTitle">vCheck v$($version) by Alan Renouf (<a href='http://virtu-al.net' target='_blank'>http://virtu-al.net</a>) generated on $($ENV:Computername)</div>
<br/>
<div class="Created">Report created on $(Get-Date)</div>
"@
Return $Report
}
Function Get-CustomHeader0 ($Title){
$Report = @"
<div class="pageholder">
<h1 class="dsp dsphead0">$($Title)</h1>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader ($Title, $cmnt){
$Report = @"
<h2 class="dsp dsphead1">$($Title)</h2>
"@
If ($Comments) {
$Report += @"
<div class="dsp dspcomments">$($cmnt)</div>
"@
}
$Report += @"
<div class="dspcont">
"@
Return $Report
}
Function Get-CustomHeaderClose{
$Report = @"
</DIV>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader0Close{
$Report = @"
</DIV>
"@
Return $Report
}
Function Get-CustomHTMLClose{
$Report = @"
</div>
</body>
</html>
"@
Return $Report
}
Function Get-HTMLTable {
param([array]$Content)
$HTMLTable = $Content | ConvertTo-Html
$HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', ""
$HTMLTable = $HTMLTable -replace '<html>', ""
$HTMLTable = $HTMLTable -replace '<head>', ""
$HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', ""
$HTMLTable = $HTMLTable -replace '</head><body>', ""
$HTMLTable = $HTMLTable -replace '</body></html>', ""
$HTMLTable = $HTMLTable -replace '<', "<"
$HTMLTable = $HTMLTable -replace '>', ">"
Return $HTMLTable
}
Function Get-HTMLDetail ($Heading, $Detail){
$Report = @"
<TABLE>
<tr>
<th width='50%'><b>$Heading</b></font></th>
<td width='50%'>$($Detail)</td>
</tr>
</TABLE>
"@
Return $Report
}
Function Find-Username ($username){
if ($username -ne $null)
{
$root = [ADSI]""
$filter = ("(&(objectCategory=user)(samAccountName=$Username))")
$ds = new-object system.DirectoryServices.DirectorySearcher($root,$filter)
$ds.PageSize = 1000
$UN = $ds.FindOne()
If ($UN -eq $null){
Return $username
}
Else {
Return $UN
}
}
}
function Get-VIServices
{
If ($SetUsername -ne ""){
$Services = get-wmiobject win32_service -Credential $creds -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" }
} Else {
$Services = get-wmiobject win32_service -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" }
}
$myCol = @()
Foreach ($service in $Services){
$MyDetails = "" | select-Object Name, State, StartMode, Health
If ($service.StartMode -eq "Auto")
{
if ($service.State -eq "Stopped")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "Unexpected State"
}
}
If ($service.StartMode -eq "Auto")
{
if ($service.State -eq "Running")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "OK"
}
}
If ($service.StartMode -eq "Disabled")
{
If ($service.State -eq "Running")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "Unexpected State"
}
}
If ($service.StartMode -eq "Disabled")
{
if ($service.State -eq "Stopped")
{
$MyDetails.Name = $service.Displayname
$MyDetails.State = $service.State
$MyDetails.StartMode = $service.StartMode
$MyDetails.Health = "OK"
}
}
$myCol += $MyDetails
}
Write-Output $myCol
}
function Get-DatastoreSummary {
param(
$InputObject = $null
)
process {
if ($InputObject -and $_) {
throw 'The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.'
return
}
$processObject = $(if ($InputObject) {$InputObject} else {$_})
if ($processObject) {
$myCol = @()
foreach ($ds in $_)
{
$MyDetails = "" | select-Object Name, CapacityMB, FreeSpaceMB, PercFreeSpace
$MyDetails.Name = $ds.Name
#$MyDetails.Type = $ds.Type
$MyDetails.CapacityMB = $ds.CapacityMB
$MyDetails.FreeSpaceMB = $ds.FreeSpaceMB
$MyDetails.PercFreeSpace = [math]::Round(((100 * ($ds.FreeSpaceMB)) / ($ds.CapacityMB)),0)
$myCol += $MyDetails
}
$myCol | Where { $_.PercFreeSpace -lt $DatastoreSpace }
}
}
end {
}
}
function Get-SnapshotSummary {
param(
$InputObject = $null
)
PROCESS {
if ($InputObject -and $_) {
throw 'ParameterBinderStrings\AmbiguousParameterSet'
break
} elseif ($InputObject) {
$InputObject
} elseif ($_) {
$mySnaps = @()
foreach ($snap in $_){
$SnapshotInfo = Get-SnapshotExtra $snap
$mySnaps += $SnapshotInfo
}
$mySnaps | Select VM, Name, @{N="DaysOld";E={((Get-Date) - $_.Created).Days}}, @{N="Creator";E={(Find-Username (($_.Creator.split("\"))[1])).Properties.displayname}}, SizeMB, Created, Description -ErrorAction SilentlyContinue | Sort DaysOld
} else {
throw 'ParameterBinderStrings\InputObjectNotBound'
}
}
}
function Get-SnapshotTree{
param($tree, $target)
$found = $null
foreach($elem in $tree){
if($elem.Snapshot.Value -eq $target.Value){
$found = $elem
continue
}
}
if($found -eq $null -and $elem.ChildSnapshotList -ne $null){
$found = Get-SnapshotTree $elem.ChildSnapshotList $target
}
return $found
}
function Get-SnapshotExtra ($snap){
$guestName = $snap.VM # The name of the guest
$tasknumber = 999 # Windowsize of the Task collector
$taskMgr = Get-View TaskManager
# Create hash table. Each entry is a create snapshot task
$report = @{}
$filter = New-Object VMware.Vim.TaskFilterSpec
$filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime
$filter.Time.beginTime = (($snap.Created).AddDays(-5))
$filter.Time.timeType = "startedTime"
$collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter))
$dummy = $collectionImpl.RewindCollector
$collection = $collectionImpl.ReadNextTasks($tasknumber)
while($collection -ne $null){
$collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{
$row = New-Object PsObject
$row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reason.UserName
$vm = Get-View $_.Entity
if($vm -ne $null){
$snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result
if($snapshot -ne $null){
$key = $_.EntityName + "&" + ($snapshot.CreateTime.ToString())
$report[$key] = $row
}
}
}
$collection = $collectionImpl.ReadNextTasks($tasknumber)
}
$collectionImpl.DestroyCollector()
# Get the guest's snapshots and add the user
$snapshotsExtra = $snap | % {
$key = $_.vm.Name + "&" + ($_.Created.ToString())
if($report.ContainsKey($key)){
$_ | Add-Member -MemberType NoteProperty -Name Creator -Value $report[$key].User
}
$_
}
$snapshotsExtra
}
Function Set-Cred ($File) {
$Credential = Get-Credential
$credential.Password | ConvertFrom-SecureString | Set-Content $File
}
Function Get-Cred ($User,$File) {
$password = Get-Content $File | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($user,$password)
$credential
}
function Get-UnShareableDatastore {
$Report = @()
Foreach ($datastore in (Get-Datastore)){
If (($datastore | get-view).summary.multiplehostaccess -eq $false){
ForEach ($VM in (get-vm -datastore $Datastore )){
$SAHost = "" | Select VM, Datastore
$SAHost.VM = $VM.Name
$SAHost.Datastore = $Datastore.Name
$Report += $SAHost
}
}
}
$Report
}
If ($SetUsername -ne ""){
if ((Test-Path -Path $CredFile) -eq $false) {
Set-Cred $CredFile
}
$creds = Get-Cred $SetUsername $CredFile
}
Write-CustomOut "Connecting to VI Server"
$VIServer = Connect-VIServer $VISRV
If ($VIServer.IsConnected -ne $true){
# Fix for scheduled tasks not running.
$USER = $env:username
$APPPATH = "C:\Documents and Settings\" + $USER + "\Application Data"
#SET THE APPDATA ENVIRONMENT WHEN NEEDED
if ($env:appdata -eq $null -or $env:appdata -eq 0)
{
$env:appdata = $APPPATH
}
$VIServer = Connect-VIServer $VISRV
If ($VIServer.IsConnected -ne $true){
Write $VIServer
send-SMTPmail -to $EmailTo -from $EmailFrom -subject "ERROR: $VISRV vCheck" -smtpserver $SMTPSRV -body "The Connect-VISERVER Cmdlet did not work, please check you VI Server."
exit
}
}
# Find out which version of the API we are connecting to
If ((Get-View ServiceInstance).Content.About.Version -ge "4.0.0"){
$VIVersion = 4
}
Else{
$VIVersion = 3
}
Write-CustomOut "Collecting VM Objects"
$VM = Get-VM | Sort Name
Write-CustomOut "Collecting VM Host Objects"
$VMH = Get-VMHost | Sort Name
Write-CustomOut "Collecting Cluster Objects"
$Clusters = Get-Cluster | Sort Name
Write-CustomOut "Collecting Datastore Objects"
$Datastores = Get-Datastore | Sort Name
Write-CustomOut "Collecting Detailed VM Objects"
$FullVM = Get-View -ViewType VirtualMachine | Where {-not $_.Config.Template}
Write-CustomOut "Collecting Template Objects"
$VMTmpl = Get-Template
Write-CustomOut "Collecting Detailed VI Objects"
$serviceInstance = get-view ServiceInstance
Write-CustomOut "Collecting Detailed Alarm Objects"
$alarmMgr = get-view $serviceInstance.Content.alarmManager
Write-CustomOut "Collecting Detailed VMHost Objects"
$HostsViews = Get-View -ViewType hostsystem
$Date = Get-Date
# Check for vSphere
If ($serviceInstance.Client.ServiceContent.About.Version -ge 4){
$vSphere = $true
}
$MyReport = Get-CustomHTML "$VIServer vCheck"
$MyReport += Get-CustomHeader0 ($VIServer.Name)
# ---- General Summary Info ----
If ($ShowGenSum){
Write-CustomOut "..Adding General Summary Info to the report"
$CommentsSet = $Comments
$Comments = $false
$MyReport += Get-CustomHeader "General Details" ""
$MyReport += Get-HTMLDetail "Number of Hosts:" (@($VMH).Count)
$MyReport += Get-HTMLDetail "Number of VMs:" (@($VM).Count)
$MyReport += Get-HTMLDetail "Number of Templates:" (@($VMTmpl).Count)
$MyReport += Get-HTMLDetail "Number of Clusters:" (@($Clusters).Count)
$MyReport += Get-HTMLDetail "Number of Datastores:" (@($Datastores).Count)
$MyReport += Get-HTMLDetail "Active VMs:" (@($FullVM | Where { $_.Runtime.PowerState -eq "poweredOn" }).Count)
$MyReport += Get-HTMLDetail "In-active VMs:" (@($FullVM | Where { $_.Runtime.PowerState -eq "poweredOff" }).Count)
$MyReport += Get-HTMLDetail "DRS Migrations for last $($DRSMigrateAge) Days:" @(Get-VIEvent -maxsamples 10000 -Start ($Date).AddDays(-$DRSMigrateAge ) | where {$_.Gettype().Name -eq "DrsVmMigratedEvent"}).Count
$Comments = $CommentsSet
$MyReport += Get-CustomHeaderClose
}
# Capacity Planner Info
if ($ShowCapacityInfo){
Write-CustomOut "..Checking Capacity Info"
$capacityinfo = @()
foreach ($cluv in (Get-View -ViewType ClusterComputeResource)){
if ((Get-Cluster $cluv.name|Get-VM).count -gt 0){
$clucapacity = "" |Select ClusterName, "Estimated Num VM Left (CPU)", "Estimated Num VM Left (MEM)"
#CPU
$DasRealCpuCapacity = $cluv.Summary.EffectiveCpu - (($cluv.Summary.EffectiveCpu*$cluv.Configuration.DasConfig.FailoverLevel)/$cluv.Summary.NumEffectiveHosts)
$CluCpuUsage = get-stat -entity $cluv.name -stat cpu.usagemhz.average -Start ($Date).adddays(-7) -Finish ($Date)
$CluCpuUsageAvg = ($CluCpuUsage|Where-object{$_.value -gt ($CluCpuUsage|Measure-Object -average -Property value).average}|Measure-Object -Property value -Average).Average
$VmCpuAverage = $CluCpuUsageAvg/(Get-Cluster $cluv.name|Get-VM).count
$CpuVmLeft = [math]::round(($DasRealCpuCapacity-$CluCpuUsageAvg)/$VmCpuAverage,0)
#MEM
$DasRealMemCapacity = $cluv.Summary.EffectiveMemory - (($cluv.Summary.EffectiveMemory*$cluv.Configuration.DasConfig.FailoverLevel)/$cluv.Summary.NumEffectiveHosts)
$CluMemUsage = get-stat -entity $cluv.name -stat mem.consumed.average -Start ($Date).adddays(-7) -Finish ($Date)
$CluMemUsageAvg = ($CluMemUsage|Where-object{$_.value -gt ($CluMemUsage|Measure-Object -average -Property value).average}|Measure-Object -Property value -Average).Average/1024
$VmMemAverage = $CluMemUsageAvg/(Get-Cluster $cluv.name|Get-VM).count
$MemVmLeft = [math]::round(($DasRealMemCapacity-$CluMemUsageAvg)/$VmMemAverage,0)
$clucapacity.ClusterName = $cluv.name
$clucapacity."Estimated Num VM Left (CPU)" = $CpuVmLeft
$clucapacity."Estimated Num VM Left (MEM)" = $MemVmLeft
$capacityinfo += $clucapacity
}
}
If (($capacityinfo | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Capacity Planner Info" "The following gives brief capacity information for each cluster based on average CPU/Mem usage and counting for HA failover requirements"
$MyReport += Get-HTMLTable $capacityinfo
$MyReport += Get-CustomHeaderClose
}
}
# ---- Snapshot Information ----
If ($ShowSnap){
Write-CustomOut "..Checking Snapshots"
$Snapshots = @($VM | Get-Snapshot | Where {$_.Created -lt (($Date).AddDays(-$SnapshotAge))} | Get-SnapshotSummary)
If (($Snapshots | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Snapshots (Over $SnapshotAge Days Old) : $($snapshots.count)" "VMware snapshots which are kept for a long period of time may cause issues, filling up datastores and also may impact performance of the virtual machine."
$MyReport += Get-HTMLTable $Snapshots
$MyReport += Get-CustomHeaderClose
}
}
# ---- Datastore Information ----
If ($Showdata){
Write-CustomOut "..Checking Datastores"
$OutputDatastores = @($Datastores | Get-DatastoreSummary | Sort PercFreeSpace)
If (($OutputDatastores | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Datastores (Less than $DatastoreSpace% Free) : $($OutputDatastores.count)" "Datastores which run out of space will cause impact on the virtual machines held on these datastores"
$MyReport += Get-HTMLTable $OutputDatastores
$MyReport += Get-CustomHeaderClose
}
}
# ---- Map disk region ----
If ($ShowMapDiskRegionEvents){
Write-CustomOut "..Checking for Map disk region event"
$MapDiskRegionEvents = @($VIEvent | Where {$_.FullFormattedMessage -match "Map disk region"} | Foreach {$_.vm}|select name |Sort-Object -unique)
If (($MapDiskRegionEvents | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Map disk region event (Last $VMsNewRemovedAge Day(s)) : $($MapDiskRegionEvents.count)" "These may occur due to VCB issues, check <a href='http://kb.vmware.com/kb/1007331' target='_blank'>this article</a> for more details "
$MyReport += Get-HTMLTable $MapDiskRegionEvents
$MyReport += Get-CustomHeaderClose
}
}
# ---- Hosts in Maintenance Mode ----
If ($ShowMaint){
Write-CustomOut "..Checking Hosts in Maintenance Mode"
$MaintHosts = @($VMH | where {$_.State -match "Maintenance"} | Select Name, State)
If (($MaintHosts | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Hosts in Maintenance Mode : $($MaintHosts.count)" "Hosts held in Maintenance mode will not be running any virtual machine worloads, check the below Hosts are in an expected state"
$MyReport += Get-HTMLTable $MaintHosts
$MyReport += Get-CustomHeaderClose
}
}
# ---- Hosts Not responding or Disconnected ----
If ($ShowResDis){
Write-CustomOut "..Checking Hosts Not responding or Disconnected"
$RespondHosts = @($VMH | where {$_.State -ne "Connected" -and $_.State -ne "Maintenance"} | get-view | Select name, @{N="Connection State";E={$_.Runtime.ConnectionState}}, @{N="Power State";E={$_.Runtime.PowerState}})
If (($RespondHosts | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Hosts not responding or disconnected : $($RespondHosts.count)" "Hosts which are in a disconnected state will not be running any virtual machine worloads, check the below Hosts are in an expected state"
$MyReport += Get-HTMLTable $RespondHosts
$MyReport += Get-CustomHeaderClose
}
}
# ---- Hosts which are overcomitting ----
If ($ShowOvercommit){
Write-CustomOut "..Checking Hosts Overcommit state"
$MyObj = @()
Foreach ($VMHost in $VMH) {
$Details = "" | Select Host, TotalMemMB, TotalAssignedMemMB, TotalUsedMB, OverCommitMB
$Details.Host = $VMHost.Name
$Details.TotalMemMB = $VMHost.MemoryTotalMB
if ($VMMem) { Clear-Variable VMMem }
Get-VMHost $VMHost | Get-VM | Foreach {
[INT]$VMMem += $_.MemoryMB
}
$Details.TotalAssignedMemMB = $VMMem
$Details.TotalUsedMB = $VMHost.MemoryUsageMB
If ($Details.TotalAssignedMemMB -gt $VMHost.MemoryTotalMB) {
$Details.OverCommitMB = ($Details.TotalAssignedMemMB - $VMHost.MemoryTotalMB)
} Else {
$Details.OverCommitMB = 0
}
$MyObj += $Details
}
$OverCommit = @($MyObj | Where {$_.OverCommitMB -gt 0})
If (($OverCommit | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Hosts overcommiting memory : $($OverCommit.count)" "Overcommitted hosts may cause issues with performance if memory is not issued when needed, this may cause ballooning and swapping"
$MyReport += Get-HTMLTable $OverCommit
$MyReport += Get-CustomHeaderClose
}
}
# ---- Dead LunPath ----
If ($ShowLunPath){
Write-CustomOut "..Checking Hosts Dead Lun Path"
$deadluns = @()
foreach ($esxhost in ($VMH | where {$_.State -eq "Connected" -or $_.State -eq "Maintenance"}))
{
$esxluns = Get-ScsiLun -vmhost $esxhost |Get-ScsiLunPath
foreach ($esxlun in $esxluns){
if ($esxlun.state -eq "Dead") {
$myObj = "" |
Select VMHost, Lunpath, State
$myObj.VMHost = $esxhost
$myObj.Lunpath = $esxlun.Lunpath
$myObj.State = $esxlun.state
$deadluns += $myObj
}
}
}
If (($deadluns | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "Dead LunPath : $($deadluns.count)" "Dead LUN Paths may cause issues with storage performance or be an indication of loss of redundancy"
$MyReport += Get-HTMLTable $deadluns
$MyReport += Get-CustomHeaderClose
}
}
# ---- VMs created or Cloned ----
If ($ShowCreated){
Write-CustomOut "..Checking for created or cloned VMs"
$VIEvent = Get-VIEvent -maxsamples 10000 -Start ($Date).AddDays(-$VMsNewRemovedAge)
$OutputCreatedVMs = @($VIEvent | where {$_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmBeingClonedEvent" -or $_.Gettype().Name -eq "VmBeingDeployedEvent"} | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\"))[1])).Properties.displayname}}, fullFormattedMessage)
If (($OutputCreatedVMs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "VMs Created or Cloned (Last $VMsNewRemovedAge Day(s)) : $($OutputCreatedVMs.count)" "The following VMs have been created over the last $($VMsNewRemovedAge) Days"
$MyReport += Get-HTMLTable $OutputCreatedVMs
$MyReport += Get-CustomHeaderClose
}
}
# ---- VMs Removed ----
If ($ShowRemoved){
Write-CustomOut "..Checking for removed VMs"
$OutputRemovedVMs = @($VIEvent | where {$_.Gettype().Name -eq "VmRemovedEvent"}| Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\"))[1])).Properties.displayname}}, fullFormattedMessage)
If (($OutputRemovedVMs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "VMs Removed (Last $VMsNewRemovedAge Day(s)) : $($OutputRemovedVMs.count)" "The following VMs have been removed/deleted over the last $($VMsNewRemovedAge) days"
$MyReport += Get-HTMLTable $OutputRemovedVMs
$MyReport += Get-CustomHeaderClose
}
}
# ---- VMs vCPU ----
If ($Showvcpu){
Write-CustomOut "..Checking for VMs with over $vCPU vCPUs"
$OverCPU = @($VM | Where {$_.NumCPU -gt $vCPU} | Select Name, PowerState, NumCPU)
If (($OverCPU | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "VMs with over $vCPU vCPUs : $($OverCPU.count)" "The following VMs have over $vCPU CPU(s) and may impact performance due to CPU scheduling"
$MyReport += Get-HTMLTable $OverCPU
$MyReport += Get-CustomHeaderClose
}
}
# ---- VMs Swapping or Ballooning ----
If ($ShowSwapBal){
Write-CustomOut "..Checking for VMs swapping or Ballooning"
$BALSWAP = $vm | Where {$_.PowerState -eq "PoweredOn" }| Select Name, Host, @{N="SwapKB";E={(Get-Stat -Entity $_ -Stat mem.swapped.average -Realtime -MaxSamples 1 -ErrorAction SilentlyContinue).Value}}, @{N="MemBalloonKB";E={(Get-Stat -Entity $_ -Stat mem.vmmemctl.average -Realtime -MaxSamples 1 -ErrorAction SilentlyContinue).Value}}
$bs = @($BALSWAP | Where { $_.SwapKB -gt 0 -or $_.MemBalloonKB -gt 0}) | Sort SwapKB -Descending
If (($bs | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "VMs Ballooning or Swapping : $($bs.count)" "Ballooning and swapping may indicate a lack of memory or a limit on a VM, this may be an indication of not enough memory in a host or a limit held on a VM, <a href='http://www.virtualinsanity.com/index.php/2010/02/19/performance-troubleshooting-vmware-vsphere-memory/' target='_blank'>further information is available here</a>."
$MyReport += Get-HTMLTable $bs
$MyReport += Get-CustomHeaderClose
}
}
# invalid or inaccessible VM
if ($ShowBlindedVM) {
Write-CustomOut "..Checking invalid or inaccessible VM"
$BlindedVM = $FullVM|?{$_.Runtime.ConnectionState -eq "invalid" -or $_.Runtime.ConnectionState -eq "inaccessible"}|sort name |select name
If (($BlindedVM | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "VM invalid or inaccessible : $(($BlindedVM | Measure-Object).count)" "The following VMs are marked as inaccessible or invalid"
$MyReport += Get-HTMLTable $BlindedVM
$MyReport += Get-CustomHeaderClose
}
}
# ---- HA VM reset log ----
If ($HAVMreset){
Write-CustomOut "..Checking HA VM reset"
$HAVMresetlist = @(Get-VIEvent -maxsamples 100000 -Start ($Date).AddDays(-$HAVMresetold) -type info |?{$_.FullFormattedMessage -match "reset due to a guest OS error"} |select CreatedTime,FullFormattedMessage |sort CreatedTime -Descending)
If (($HAVMresetlist | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "HA VM reset (Last $HAVMresetold Day(s)) : $($HAVMresetlist.count)" "The following VMs have been restarted by HA in the last $HAVMresetold days"
$MyReport += Get-HTMLTable $HAVMresetlist
$MyReport += Get-CustomHeaderClose
}
}
# ---- HA VM restart log ----
If ($HAVMrestart){
Write-CustomOut "..Checking HA VM restart"
$HAVMrestartlist = @(Get-VIEvent -maxsamples 100000 -Start ($Date).AddDays(-$HAVMrestartold) -type info |?{$_.FullFormattedMessage -match "was restarted"} |select CreatedTime,FullFormattedMessage |sort CreatedTime -Descending)
If (($HAVMrestartlist | Measure-Object).count -gt 0) {
$MyReport += Get-CustomHeader "HA VM restart (Last $HAVMrestartold Day(s)) : $($HAVMrestartlist.count)" "The following VMs have been restarted by HA in the last $HAVMresetold days"
$MyReport += Get-HTMLTable $HAVMrestartlist
$MyReport += Get-CustomHeaderClose
}
}