-
Notifications
You must be signed in to change notification settings - Fork 78
/
Assert-SQLServiceCMS.ps1
82 lines (73 loc) · 2.71 KB
/
Assert-SQLServiceCMS.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
<#
.SYNOPSIS
Provides a report of all SQL Services that are not running. Uses CMS to provide a list of servers to check.
.DESCRIPTION
Using the Central Managemetn Server as a listing for SQL Servers, the script will check all SQL services for each
server. State will be checked and if state is not "Running", the service and server will be reported.
.PARAMETER $CMS (Mandatory)
Name of the Central Management Server.
.PARAMETER $output
Defines how report is returned:
0 (default) - Format-Table output
1 - Email to specified contact.
#>
param([parameter(Mandatory=$true)][string] $CMS,
[int] $output=0)
$CMS=$CMS.replace("\", "%5C")
$srvlist = gci "SQLSERVER:\sqlregistration\Central Management Server Group\$CMSInst\" -Recurse | where {$_.ServerName -ne $null}
$report=@()
foreach ($server in $srvlist)
{
try
{
if($server.ServerName.Contains("\"))
{
$sqlhost=$server.ServerName.Substring(0,$server.ServerName.IndexOf("\"))
$instance=$server.ServerName.Substring($server.ServerName.IndexOf("\")+1)
$svcs=gwmi Win32_service -computer $sqlhost | where {$_.name -like "*$instance*"}
}
else
{
$sqlhost=$server.ServerName.Substring(0,$server.ServerName.IndexOf("\"))
$svcs=gwmi Win32_service -computer $sqlhost | where {$_.name -like "*SQLSERVER*"}
}
foreach ($svc in $svcs)
{
$output = New-Object System.Object
$output | Add-Member -type NoteProperty -name Instance -value $sqlhost
$output | Add-Member -type NoteProperty -name SvcName -value $svc.Name
$output | Add-Member -type NoteProperty -name DisplayName -value $svc.DisplayName
$output | Add-Member -type NoteProperty -name State -value $svc.State
$report+=$output
}
}
catch
{
$output = New-Object System.Object
$output | Add-Member -type NoteProperty -name Instance -value $sqlhost
$output | Add-Member -type NoteProperty -name SvcName -value "No_Service_Collected"
$output | Add-Member -type NoteProperty -name DisplayName -value "No Service Collected - COLLECTION ERROR"
$output | Add-Member -type NoteProperty -name State -value "ERROR"
$report+=$output
}
}
switch($output)
{
0 {
$report | Format-Table Instance,DisplayName,State
}
1 {
#Set these for your environment
$smtp="smtp.gmail.com"
$from="[email protected]"
$to="[email protected]"
if(($report | where {$_.State -ne "Running"}).Length -gt 0)
{
[string]$body=$report|where{$_.State -ne "Running"}| ConvertTo-HTML
Send-MailMessage -To $to -from $from -subject "Service Monitor Report" -smtpserver $smtp -body $body -BodyAsHtml
}
}
default {
$report|where{$_.State -ne "Running"} | Format-Table Instance,DisplayName,State
}
}