-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSQL-InstanceInventory.ps1
228 lines (189 loc) · 12.1 KB
/
SQL-InstanceInventory.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
<#============================================================================
Written by Christophe LAPORTE, SQL Server MVP / MCM
Blog : http://conseilit.wordpress.com
Twitter : @ConseilIT
You may alter this code for your own *non-commercial* purposes. You may
republish altered code as long as you give due credit.
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
============================================================================#>
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
clear-host
#$DiscoveredInstanceList = sqlcmd -L
# or
$DiscoveredInstanceTable = [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()
$DiscoveredInstanceList = @()
ForEach ($InstanceName in $DiscoveredInstanceTable) {
$s = $InstanceName.ServerName
if (-not ([string]::IsNullOrEmpty($InstanceName.Instancename))) {
$s += "\" + $InstanceName.Instancename
}
$DiscoveredInstanceList += $s
}
# or
# $DiscoveredInstanceList = "srv1","srv2"
try {
$AdditionalInstancesListFile = Get-Content "C:\temp\AdditionalServers.txt"
$DiscoveredInstanceList += $AdditionalInstancesListFile
}
catch {}
$ExcludedHostList = "devsql2017","(local)"
[int]$global:TotalDatabaseStorage = 0
[int]$global:TotalDatabaseCount = 0
$ListInstances = @()
$ListDatabases = @()
$InstanceErrorList = @()
$DisplayInstanceErrorList = $false
$Debug = $false
$CheckDatabaseDetails = $true
$CheckLastUserAccess = $true
$CheckSystemDatabases = $true
$OutGridView = $true
$ExportCSV = $true
$ExportCSVFile = "c:\temp\SQLInstancesInventory.csv"
ForEach ($InstanceName in $DiscoveredInstanceList) {
$InstanceName = $InstanceName.trim()
if ($InstanceName -eq "") {continue}
if ($InstanceName -eq "Servers:") {continue}
# Check excluded instances
if ($ExcludedHostList -contains $InstanceName) {
if ($Debug) {
Write-Host $InstanceName " excluded" -ForegroundColor yellow
}
continue
}
$Server = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server($InstanceName)
$Server.ConnectionContext.ConnectTimeout = 1
if (!($Server.ComputerNamePhysicalNetBIOS)) {
$InstanceErrorList += "Error connecting $InstanceName"
continue
}
else {
$Databases = $server.Databases | Where-Object Status -eq "normal" | sort-object ID
Write-Host $InstanceName "-"$Server.Edition "-" $Server.VersionString "(" $Server.ProductLevel ") -" $Server.collation `
$InstanceStorage = 0
$DatabaseCount = 0
foreach ($Database in $Databases) {
try {
If (($CheckSystemDatabases) -or ($Database.iD -gt 4)) {
$InstanceStorage += $Database.size
$DatabaseCount += 1
if ($CheckDatabaseDetails) {
if ($debug) {
Write-Host " " $Database.Name "- Owner" $Database.Owner "- RecoveryModel" $Database.RecoveryModel "- Size" $Database.Size.ToString("N") "MB"
}
if ($CheckLastUserAccess) {
$tSQL = "SELECT database_id ,
CASE WHEN max(last_user_seek) > max(last_user_scan) THEN max(last_user_seek)
ELSE max(last_user_scan)
END AS LastUserRead,
max(last_user_update) as LastUserWrite
FROM sys.dm_db_index_usage_stats
WHERE database_id = " + $Database.ID + "
GROUP BY database_id "
$LastUserRead = $Database.ExecuteWithResults($tSQL).Tables[0].LastUserRead
$LastUserWrite = $Database.ExecuteWithResults($tSQL).Tables[0].LastUserWrite
if (-not ([string]::IsNullOrEmpty($LastUserRead))) {$LastUserRead = $LastUserRead.ToString("yyyy-MM-dd HH:mm:ss")}
if (-not ([string]::IsNullOrEmpty($LastUserWrite))) {$LastUserWrite = $LastUserWrite.ToString("yyyy-MM-dd HH:mm:ss")}
}
else {
$LastUserRead = ""
$LastUserWrite = ""
}
$LastKnownGood = $($Database.ExecuteWithResults("DBCC DBINFO() WITH TABLERESULTS").Tables[0] | Where-Object {$_.Field -eq "dbi_dbccLastKnownGood"} | Select-Object -First 1).value
$ListDatabases += New-Object PSObject -Property @{InstanceName=$Server.name;`
VersionMajor=$Server.VersionMajor;`
DatabaseName=$Database.Name;`
CompatibilityLevel=$Database.CompatibilityLevel.ToString().replace("Version","");`
RecoveryModel=$Database.RecoveryModel;`
Size=$Database.Size.ToString("N");`
Owner=$Database.Owner;`
Collation=$Database.collation;`
AutoClose=$Database.AutoClose;`
AutoShrink=$Database.AutoShrink;`
IsReadCommittedSnapshotOn=$Database.IsReadCommittedSnapshotOn;`
PageVerify=$Database.PageVerify;`
ActiveConnections=$Database.ActiveConnections;`
CreateDate=$database.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");`
LastFullBackupDate=$database.LastBackupDate.ToString("yyyy-MM-dd HH:mm:ss");`
LastLogBackupDate=$database.LastLogBackupDate.ToString("yyyy-MM-dd HH:mm:ss");`
LastKnownGood=$LastKnownGood;`
LastUserRead=$LastUserRead;`
LastUserWrite=$LastUserWrite;`
}
}
}
}
catch {
Write-host -ForegroundColor Red $_.Exception.Message
}
}
$global:TotalDatabaseStorage += $InstanceStorage
$global:TotalDatabaseCount += $DatabaseCount
if ($Debug) {
Write-Host $InstanceName ": " $DatabaseCount " Databases ("$InstanceStorage.ToString("N") "MB )"
}
$TFList = $Server.EnumActiveGlobalTraceFlags() | Where-Object Global -EQ 1 | Select-Object TraceFlag
if (-not ([string]::IsNullOrEmpty($TFList))) {
$TraceFlags = [string]::Join(",",$TFList.TraceFlag)
}
else {$TraceFlags = ""}
$ListInstances += New-Object PSObject -Property @{NetName=$Server.NetName;`
InstanceName=$Server.name;`
Edition=$Server.Edition;`
VersionMajor=$Server.VersionMajor;`
Version=$Server.VersionString;`
ProductLevel=$Server.ProductLevel;`
Collation=$Server.collation;`
Processors=$server.Processors;`
PhysicalMemory=$Server.PhysicalMemory;`
MaxServerMemory=$Server.Configuration.MaxServerMemory.RunValue;`
DatabaseCount=$DatabaseCount;`
TotalSizeMB=$InstanceStorage.ToString("N");`
ServiceAccount=$Server.ServiceAccount;`
LoginMode=$Server.LoginMode;`
DatabaseEngineType=$Server.DatabaseEngineType;`
ActiveSessions=$server.EnumProcesses($false).Rows.Count;`
TraceFlags=$TraceFlags;`
}
}
}
if ($OutGridView) {
$ListInstances | Sort-Object InstanceName | Select-Object NetName, InstanceName,Edition,VersionMajor,Version,ProductLevel,`
Collation,Processors,PhysicalMemory,MaxServerMemory,DatabaseCount,`
TotalSizeMB,ServiceAccount,LoginMode,DatabaseEngineType,ActiveSessions,TraceFlags | `
Out-GridView
if ($CheckDatabaseDetails) {
$ListDatabases | Sort-Object InstanceName,DatabaseName | Select-Object InstanceName,VersionMajor,DatabaseName,CompatibilityLevel,`
ActiveConnections,RecoveryModel,Collation,AutoClose,AutoShrink,`
IsReadCommittedSnapshotOn,PageVerify,Size,Owner,CreateDate,`
LastFullBackupDate,LastLogBackupDate,LastKnownGood,LastUserRead,LastUserWrite | `
Out-GridView
}
}
if ($ExportCSV) {
$ListInstances | Sort-Object InstanceName | Select-Object NetName, InstanceName,Edition,VersionMajor,Version,ProductLevel,`
Collation,Processors,PhysicalMemory,MaxServerMemory,DatabaseCount,`
TotalSizeMB,ServiceAccount,LoginMode,DatabaseEngineType,ActiveSessions,TraceFlags | `
Export-Csv $ExportCSVFile -NoTypeInformation -Force -Delimiter ";"
if ($CheckDatabaseDetails) {
$ListDatabases | Sort-Object InstanceName,DatabaseName | Select-Object InstanceName,VersionMajor,DatabaseName,CompatibilityLevel,`
ActiveConnections,RecoveryModel,Collation,AutoClose,AutoShrink,`
IsReadCommittedSnapshotOn,PageVerify,Size,Owner,CreateDate,`
LastFullBackupDate,LastLogBackupDate,LastKnownGood,LastUserRead,LastUserWrite | `
Export-Csv $ExportCSVFile -NoTypeInformation -Force -Delimiter ";"
}
}
# Display grand total
if ($global:TotalDatabaseCount -gt 0) {
write-host ""
write-host "Grand Total :"
Write-Host $global:TotalDatabaseCount " Databases ("$global:TotalDatabaseStorage.ToString("N") "MB )"
}
if ($DisplayInstanceErrorList) {
write-host ""
write-host "Errors :"
$InstanceErrorList
}