-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInvoke-SQL-Error-Log-Audit.ps1
More file actions
68 lines (59 loc) · 1.78 KB
/
Copy pathInvoke-SQL-Error-Log-Audit.ps1
File metadata and controls
68 lines (59 loc) · 1.78 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
# ---------- SERVER LIST ----------
$servers = @(
@{Server=""; Database=""; User=""; Password=""},
@{Server=""; Database=""; User=""; Password=""}
)
# ---------- OUTPUT FILE ----------
$outputFile = "C:\Script\Error_Log_Summary.csv"
# ---------- INITIALIZE RESULT ARRAY (IMPORTANT) ----------
$allResults = @()
# ---------- QUERY ----------
$query = "
SELECT ErrorMessage, ErrorProcedure, ErrorTime
FROM ErrorLog
WHERE ErrorTime >= DATEADD(DAY, 1, EOMONTH(GETDATE(), -1))
ORDER BY ErrorTime
"
foreach ($s in $servers) {
try {
$data = Invoke-Sqlcmd `
-ServerInstance $s.Server `
-Database $s.Database `
-Username $s.User `
-Password $s.Password `
-Query $query `
-ErrorAction Stop
if ($data) {
foreach ($row in $data) {
$allResults += [PSCustomObject]@{
Server = $s.Server
Database = $s.Database
ErrorMessage = $row.ErrorMessage
ErrorProcedure = $row.ErrorProcedure
ErrorTime= $row.ErrorTime
}
}
}
}
catch {
# Capture connection failure into CSV
$allResults += [PSCustomObject]@{
Server = $s.Server
Database = $s.Database
ErrorMessage = "CONNECTION FAILED"
ErrorProcedure = ""
ErrorTime = ""
}
}
}
# ---------- EXPORT CSV (SAFE) ----------
if ($allResults.Count -gt 0) {
$allResults | Export-Csv $outputFile -NoTypeInformation
Write-Host "CSV created: $outputFile"
} else {
Write-Host "No data found. CSV not created."
}
# ---------- OPEN CSV ----------
if (Test-Path $outputFile) {
Start-Process $outputFile
}