This repository was archived by the owner on Jan 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet-EventLogSpan.ps1
479 lines (296 loc) · 14.6 KB
/
Get-EventLogSpan.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
Function Get-EventLogSpan {
<#
.SYNOPSIS
Function for veryfing Windows events log span - how old is the oldest available log event entry
.DESCRIPTION
As a result for this function you receive range between the oldest event log entry and the when the script was started - eg. 3 days 7 hours ...
.PARAMETER ComputerName
Computer which need to queried.
.PARAMETER LogsScope
You can select between Classic and All - default is Classic,
For basic installation Windows Server 2008 R2 these logs are: Application, Security, Setup, System, Forwarded Events.
All logs means that also "Applications and Services Logs" will be included - query all logs can be time consuming because LogParse can't be used for it.
.ExcludeEmptyLogs
By default empty logs are excluded from results.
.WarningLevelDays
The amount od days for which log can be marked in results as Warning if the span of logs is smaller than warning level.
Default warning level is set to 30 days.
.CriticalLevelDays
The amount od days for which log can be marked in results as Critical if the span of logs is smaller than warning level.
Default warning level is set to 7 days.
.OutputDirection
Default output direction is Console - result is returned as PowerShell object so can be simply redirected to pipe.
In the future output to HTML file and email will be implemented also.
.ColourOutput
By default output will be displayed using different colors for Critical and Warning log span levels.
In thi moment colors can be changed only by editing source code.
.LogParserInstalled
Use this parameter (set to $false) if Log Parser is not installed, the native PowerShell cmdlet will be used to parse all event logs.
If set to $false log parsing will be much slower - due to use PowerShell native command to find the oldes log event entry.
.EXAMPLE
Get-EventLogSpan -ComputerName localhost -LogsScope Classic -WarningLevelDays 14
LogName : Application
LogSpanStatus : Normal
ComputerName : localhost
OldestEventTime : 2013-12-06 00:45:13
LogTimeSpan : 430.23:02:55.7739014
LogName : Security
LogSpanStatus : Normal
ComputerName : localhost
OldestEventTime : 2013-12-06 00:44:55
LogTimeSpan : 430.23:03:13.5087764
LogName : System
LogSpanStatus : Normal
ComputerName : localhost
OldestEventTime : 2013-12-06 00:44:51
LogTimeSpan : 430.23:03:17.1181514
.LINK
https://github.com/it-praktyk/Get-EventLogSpan
.LINK
https://www.linkedin.com/in/sciesinskiwojciech
.NOTES
AUTHOR: Wojciech Sciesinski, wojciech[at]sciesinski[dot]net
KEYWORDS: Windows, PowerShell, EventLogs
BASE REPOSITORY: https://github.com/it-praktyk/Get-EventLogSpan
VERSION HISTORY
0.3.0 - 2015-01-20 - first version published on GitHub
0.4.0 - 2015-01-21 - output updated - now include timespan, warning and critical levels added as parameters, output can be coloured
0.5.0 - 2015-01-25 - checking not classic logs corrected,progress indicator added, lots improvments added
0.5.1 - 2015-01-26 - checking oldest log corrected for remote computers
0.5.2 - 2015-01-26 - checking using Log Parser corrected, output for status for empty logs corrected
0.5.3 - 2015-02-05 - double quoute to single quote changed for static strings, minor updates
0.6.0 - 2015-02-06 - check if .Net Framework 3.5 is installed - needed for Get-WinEvent cmdlet
0.6.1 - 2015-02-09 - help updated
0.6.2 - 2015-02-09 - script updated due to warning displayed by Script Analyzer e.g. positional parameter changed to named etc.
0.7.0 - 2015-02-10 - minor bugs corrected, tabs replaced to 4 spaces to normalize looks between editors, first version published on TechNet
0.8.0 - 2015-02-10 - query used for query data from remote computers by logparser corrected
0.9.0 - 2016-02-17 - Thomas Rhoads (ev3rl0ng[at]gmail[dot]com) - added check for administrator token.
0.9.1 - 2016-02-17 - Thomas Rhoads (ev3rl0ng[at]gmail[dot]com) - moved .net check to Begin section and added support for .Net > 3.5
0.9.2 - 2016-02-17 - Thomas Rhoads (ev3rl0ng[at]gmail[dot]com) - Removed Test-Key function as it is no longer used.
TODO
- HTML output need to be implemented
- email output need to bi implemented (?)
DISCLAIMER
This script is provided “as-is” and are to be used on your own responsibility. I do not accept any liability nor do I take any responsibility for using these scripts in your environment.
Please use with caution and always test them before usage!
#>
#Requires -Version 2.0
[CmdletBinding()]
param (
[parameter(mandatory=$false,Position=0)]
[String]$ComputerName='localhost',
[parameter(mandatory=$false,Position=1)]
[ValidateSet('All','Classic')]
[String]$LogsScope='Classic',
[parameter(mandatory=$false,Position=2)]
[Bool]$ExcludeEmptyLogs=$true,
[parameter(mandatory=$false,Position=3)]
[Int32]$WarningLevelDays=30,
[parameter(mandatory=$false,Position=4)]
[Int32]$CriticalLevelDays=7,
#HTML Output is not implemented yet
[parameter(mandatory=$false,Position=5)]
[ValidateSet('Console','HTML')]
[String]$OutputDirection='Console',
[parameter(mandatory=$false,Position=6)]
[Bool]$ColourOutput=$true,
[parameter(mandatory=$false,Position=7)]
[Bool]$LogParserInstalled=$true
)
Begin {
#Set-StrictMode -Version 2
# Get currently logged on principal.
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent() )
# Check for Administrator Rights bit.
If (!$currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator )) {
Write-Error -Message "This function requires elevation. Please run PowerShell as an Administrator"
Break
}
$currentPrincipal = $null
# Iterate through all .NET versions installed and determine whether we have a satisfactory version.
# Based on answer at: http://stackoverflow.com/questions/3487265/powershell-script-to-return-versions-of-net-framework-on-a-machine
$boolNetFXVersionOK = $false
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?!S)\p{L}'} |
Select PSChildName, Version, Release |
ForEach-Object {
if ($_.Version -gt 3.5) {
$boolNetFXVersionOK = $true
}
}
If (!$boolNetFXVersionOK) {
Write-Error -Message "This function requires Microsoft .NET Framework version 3.5 or greater."
Break
}
$boolNetFXVersionOK = $null
$Results=@()
$StartTime = Get-Date
$WarningColor = 'Yellow'
$CriticalColor = 'Red'
$i=0
}
Process {
If ($LogsScope -eq 'Classic') {
$Logs = Get-WinEvent -ComputerName $ComputerName -ListLog * -ErrorAction SilentlyContinue | Where-Object { $_.IsClassicLog }
}
Else {
$Logs = Get-WinEvent -ComputerName $ComputerName -ListLog * -ErrorAction SilentlyContinue
}
$LogsCount = ($Logs | Measure-Object).Count
$Logs | ForEach-Object -Process {
#Checking if Verbose parameter is not set to true
If ( !$PSCmdlet.MyInvocation.BoundParameters['Verbose'].IsPresent ) {
$StatusText = "Percent completed $PercentCompleted%, currently the log {0} is checked. " -f $($_.LogName).ToString()
If ($i -eq 0) {
$PercentCompleted = 0
}
Else {
$PercentCompleted = [math]::Round(($i / $LogsCount) * 100)
}
Write-Progress -Activity "Checking logs for $ComputerName" -Status $StatusText -PercentComplete $PercentCompleted
}
$LogTimeSpan = 0
If ( $Scope -eq 'Classic' ) {
$OldestEventEntryTime = Get-OldestEventTime -ComputerName $ComputerName -LogName $_.LogName.ToString() -Method LogParser -Verbose:($PSBoundParameters['Verbose'] -eq $true)
}
Else{
If ($_.IsClassicLog -and $LogParserInstalled ) {
$OldestEventEntryTime = Get-OldestEventTime -ComputerName $ComputerName -LogName $_.LogName.ToString() -Method LogParser -Verbose:($PSBoundParameters['Verbose'] -eq $true)
}
Else {
$OldestEventEntryTime = Get-OldestEventTime -ComputerName $ComputerName -LogName $_.LogName.ToString() -Method PowerShell -Verbose:($PSBoundParameters['Verbose'] -eq $true)
}
}
$LogSpanStatus = 'Empty'
If ($OldestEventEntryTime -ne $null ) {
$LogTimeSpan = New-TimeSpan -Start $OldestEventEntryTime -End $StartTime
If ($LogTimeSpan -lt $(New-TimeSpan -Days $WarningLevelDays) -and $LogTimeSpan -gt $(New-TimeSpan -Days $CriticalLevelDays)) {
$LogSpanStatus = 'Warning'
}
elseif ( $LogTimeSpan -lt $(New-TimeSpan -Days $CriticalLevelDays)) {
$LogSpanStatus = 'Critical'
}
else {
$LogSpanStatus = 'Normal'
}
}
$PropertiesArray = @{
ComputerName = $ComputerName
LogName = $_.LogName
OldestEventTime = $OldestEventEntryTime
LogTimeSpan = $LogTimeSpan
LogSpanStatus = $LogSpanStatus
}
$Result = New-Object -TypeName PSObject -Property $PropertiesArray
Write-Verbose -Message $Result
If (($Result.OldestEventTime -ne $null) -or !$ExcludeEmptyLogs) {
$Results+=$Result
}
$i++
}
}
End {
If ($OutputDirection -eq 'Console') {
$Results | ForEach-Object -Process {
if ($_.LogSpanStatus -eq 'Critical' -and $ColourOutput) {
Write-ColorOutput -ForeGroundColor $CriticalColor -OutputData $_
}
elseif ($_.LogSpanStatus -eq 'Warning' -and $ColourOutput) {
Write-ColorOutput -ForeGroundColor $WarningColor -OutputData $_
}
else {
Write-Output -InputObject $_
}
}
}
Else {
Write-Host -Message "Sorry, HTML output is not implemented yet. If needed please use ConvertTo-HTML cmdlet in pipeline."
#$Results | ConvertTo-HTML | OUT-FILE ".\result.htm"
}
}
}
Function Get-OldestEventTime {
[CmdletBinding()]
param (
[parameter(mandatory=$false,Position=0)]
[String]$ComputerName='localhost',
[parameter(mandatory=$false,Position=1,ValueFromPipeline=$false)]
[String]$LogName,
[parameter(mandatory=$false,Position=2)]
[ValidateSet('LogParser','PowerShell')]
[String]$Method='LogParser'
)
begin {
If ( $Method -eq 'LogParser' ) {
#Code was partially generated by Log Parser Studio tool
$LogQuery = New-Object -ComObject "MSUtil.LogQuery"
$InputFormat = New-Object -ComObject "MSUtil.LogQuery.EventLogInputFormat"
$OutputFormat = New-Object -ComObject "MSUtil.LogQuery.NativeOutputFormat"
$InputFormat.fullText=1
$InputFormat.resolveSIDs=0
$InputFormat.formatMsg=1
$InputFormat.msgErrorMode="MSG"
$InputFormat.fullEventCode=0
$InputFormat.direction="FW"
$InputFormat.stringsSep="|"
$InputFormat.binaryFormat="PRINT"
$InputFormat.ignoreMessageErrors=0
If ( $ComputerName -eq 'localhost' ) {
[String]$LogToQuery = $LogName
}
Else {
[String]$LogToQuery = '\\' + $ComputerName + '\' + $LogName
}
$SQLQuery = "SELECT TOP 1 TimeGenerated FROM '{0}' ORDER BY TimeGenerated ASC" -f $LogToQuery
Write-Verbose -Message "Query used for logparser: $SQLQuery"
}
}
process {
try{
If ($Method -eq 'LogParser') {
$rtnVal = $LogQuery.Execute($SQLQuery, $InputFormat)
do{
$lp_return = @{}
$log_entry = $rtnVal.getrecord()
$lp_return.add('TimeGenerated',[datetime]$log_entry.getvalue("TimeGenerated"))
$rtnVal.movenext()
} while ($rtnVal.atend() -eq $false)
}
Else {
$lp_return = @{}
$Oldest = Get-WinEvent -ComputerName $ComputerName -LogName $Logname -ErrorAction SilentlyContinue | Select-Object -Last 1 -ErrorAction SilentlyContinue
If ($Oldest) {
$lp_return.add('TimeGenerated', $Oldest.TimeCreated )
}
}
$Result = New-Object -TypeName PSObject -Property $lp_return
Write-Verbose -Message "The oldest event log entry in log $Logname is dated on $Result.TimeGenerated"
}
catch {
Write-Verbose -Message "The log $LogName on $ComputerName is unavailable or empty."
}
}
end {
Return $Result.TimeGenerated
}
}
function Write-ColorOutput {
param (
[parameter(mandatory=$true,Position=0)]
[String]$ForeGroundColor,
[parameter(mandatory=$true,Position=1)]
$OutputData
)
#Source
#http://stackoverflow.com/questions/4647756/is-there-a-way-to-specify-a-font-color-when-using-write-output
#Modified by Wojciech Sciesinski
# save the current color
$fc = $host.UI.RawUI.ForegroundColor
# set the new color
$host.UI.RawUI.ForegroundColor = $ForegroundColor
# Write output
Write-Output -InputObject $OutputData
# restore the original color
$host.UI.RawUI.ForegroundColor = $fc
}