-
Notifications
You must be signed in to change notification settings - Fork 17
/
event-log-manager.ps1
2060 lines (1729 loc) · 78 KB
/
event-log-manager.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
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
<#
.SYNOPSIS
powershell script to manage event logs on multiple machines
.LINK
invoke-webRequest "https://raw.githubusercontent.com/jagilber/powershellScripts/master/event-log-manager.ps1" -outFile "$pwd\event-log-manager.ps1"
.DESCRIPTION
To enable script execution, you may need to Set-ExecutionPolicy Bypass -Force
This script will optionally enable / disable debug and analytic event logs.
This can be against both local and remote machines.
It will also take a regex filter pattern for both event log names and traces.
For each match, all event logs will be exported to csv format.
Each export will be in its own file named with the event log name.
Script has ability to 'listen' to new events by continuously polling configured event logs.
Requirements:
- administrator powershell prompt
- administrative access to machine
- remote network ports:
- smb 445
- rpc endpoint mapper 135
- rpc ephemeral ports
- to test access from source machine to remote machine: dir \\%remote machine%\admin$
- winrm
- depending on configuration / security, it may be necessary to modify trustedhosts on
source machine for management of remote machines
- to query: winrm get winrm/config
- to enable sending credentials to remote machines: winrm set winrm/config/client '@{TrustedHosts="*"}'
- to disable sending credentials to remote machines: winrm set winrm/config/client '@{TrustedHosts=""}'
- firewall
- if firewall is preventing connectivity the following can be run to disable
- Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
Copyright 2017 Microsoft Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.NOTES
File Name : event-log-manager.ps1
Author : jagilber
Version : 230415 fix issue #2
History :
.EXAMPLE
.\event-log-manager.ps1 -rds -minutes 10
Example command to query rds event logs for last 10 minutes.
.EXAMPLE
.\event-log-manager.ps1 -minutes 10 -eventLogNamePattern * -machines rds-gw-1,rds-gw-2
Example command to query all event logs. It will query machines rds-gw-1 and rds-gw-2 for all events in last 10 minutes:
.EXAMPLE
.\event-log-manager.ps1 -machines rds-gw-1,rds-gw-2
Example command to query rds event logs. It will query machines rds-gw-1 and rds-gw-2 for events for today from Application and System logs (default logs):
.EXAMPLE
.\event-log-manager.ps1 -enableDebugLogs -eventLogNamePattern dns -rds
Example command to enable "debug and analytic" event logs for 'rds' event logs and 'dns' event logs:
.EXAMPLE
.\event-log-manager.ps1 -eventLogNamePattern * -eventTracePattern "fail"
Example command to export all event logs entries that have the word 'fail' in the event Message:
.EXAMPLE
.\event-log-manager.ps1 -eventLogNamePattern * -eventTracePattern "fail" -eventLogLevel Warning
Example command to export all event logs entries that have the word 'fail' in the event Message and log level 'Warning':
.EXAMPLE
.\event-log-manager.ps1 -listEventLogs -disableDebugLogs
Example command to disable "debug and analytic" event logs:
.EXAMPLE
.\event-log-manager.ps1 -cleareventlogs -eventLogNamePattern "^system$"
Example command to clear 'System' event log:
.EXAMPLE
.\event-log-manager.ps1 -eventStartTime "12/15/2015 10:00 am"
Example command to query for all events after specified time:
.EXAMPLE
.\event-log-manager.ps1 -eventStopTime "12/15/2016 10:00 am"
Example command to query for all events up to specified time:
.EXAMPLE
.\event-log-manager.ps1 -listEventLogs
Example command to query all event log names:
.EXAMPLE
.\event-log-manager.ps1 -listen -rds -machines rds-rds-1,rds-rds-2,rds-cb-1
Example command to listen to multiple machines for all eventlogs for Remote Desktop Services:
.EXAMPLE
.\event-log-manager.ps1 -eventLogPath c:\temp -eventLogNamePattern *
Example command to query path c:\temp for all *.evt* files and convert to csv:
.EXAMPLE
.\event-log-manager.ps1 -listen -rds -eventLogIds 4105 -command "powershell.exe .\somescript.ps1" -commandCount 5
Example command to listen to event logs for Remote Desktop Services for event id 4105.
If event is logged, run command "powershell.exe .\somescript.ps1 <event message>" will be started in a new process
.PARAMETER clearEventLogs
clear all event logs matching 'eventLogNamePattern'
.PARAMETER clearEventLogsOnGather
clear all event logs matching 'eventLogNamePattern' after eventlogs have been gathered.
.PARAMETER command
run a command on -eventLogIds match or -eventTracePattern match.
NOTE: requires -listen and -eventLogIds or -eventTracePattern arguments.
NOTE: by default will only run command one time but can be modified with -commandCount argument.
event string will be added to command given as a quoted argument when command is started.
see EXAMPLE
.PARAMETER commandCount
modify default value of 1 for number of times to execute command on match.
.PARAMETER days
number of days to query from the event logs. The number specified is a positive number
.PARAMETER disableDebugLogs
disable the 'analytic and debug' event logs matching 'eventLogNamePattern'
.PARAMETER displayMergedResults
display merged results in default viewer for .csv files.
.PARAMETER enableDebugLogs
enable the 'analytic and debug' event logs matching 'eventLogNamePattern'
NOTE: at end of troubleshooting, remember to 'disableEventLogs' as there is disk and cpu overhead for debug logs
WARNING: enabling too many debug eventlogs can make system non responsive and may make machine unbootable!
Only enable specific debug logs needed and only while troubleshooting.
.PARAMETER eventDetails
output event log items including xml data found on 'details' tab.
.PARAMETER eventDetailsFormatted
output event log items including xml data found on 'details' tab with xml formatted.
.PARAMETER eventLogIds
comma separated list of event logs id's to query.
Default is all id's.
.PARAMETER eventLogLevels
comma separated list of event log levels to query.
Default is all event levels.
Options are Critical,Error,Warning,Information,Verbose
.PARAMETER eventLogNamePattern
string or regex pattern to specify event log names to modify / query.
If not specified, the default value is for 'Application' and 'System' event logs
If 'rds $true' and this argument is not specified, the following regex will be used "RemoteApp|RemoteDesktop|Terminal"
.PARAMETER eventLogPath
If specified as a directory, will be used as a directory path to search for .evt and .evtx files.
If specified as a file, will be used as a file path to open .evt or .evtx file.
This parameter is not compatible with '-machines'
.PARAMETER eventStartTime
time and / or date string that can be used as a starting time to query event logs
If not specified, the default is for today only
.PARAMETER eventStopTime
time and / or date string that can be used as a stopping time to query event logs
If not specified, the default is for current time
.PARAMETER eventTracePattern
string or regex pattern to specify event log traces to query.
If not specified, all traces matching other criteria are displayed
.PARAMETER getUpdate
compare the current script against the location in github and will update if different.
.PARAMETER hours
number of hours to query from the event logs. The number specified is a positive number
.PARAMETER listen
listen and display new events from event logs matching specifed pattern with eventlognamepattern
.PARAMETER listeventlogs
list all eventlogs matching specified pattern with eventlognamepattern
.PARAMETER machines
run script against remote machine(s). List is comma separated. argument also accepts file name and path of text file
with machine names.
If not specified, script will run against local machine
.PARAMETER merge
merge all .csv output files into one file sorted by time
.PARAMETER minutes
number of minutes to query from the event logs. The number specified is a positive number
.PARAMETER months
number of months to query from the event logs. The number specified is a positive number
.PARAMETER noDynamicPath
store output files in a non-timestamped folder which is useful if calling from another script.
.PARAMETER rds
set the default 'eventLogNamePattern' to "RemoteApp|RemoteDesktop|Terminal" if value not populated
.PARAMETER uploadDir
directory where all files will be created.
default is .\gather
.LINK
https://aka.ms/event-log-manager.ps1
https://github.com/jagilber/powershellScripts
#>
[CmdletBinding()]
Param(
[string] $eventLogNamePattern = "",
[string] $eventLogPath = "",
[string] $eventStartTime,
[string] $eventStopTime,
[string] $eventTracePattern = "",
[string] $uploadDir,
[switch] $merge,
[string[]] $machines = @(),
[int] $months = 0,
[int] $days = 0,
[int] $hours = 0,
[int] $minutes = 0,
[switch] $disableDebugLogs,
[switch] $displayMergedResults,
[switch] $enableDebugLogs,
[switch] $eventDetails,
[switch] $eventDetailsFormatted,
[string[]] $eventLogLevels = @("critical", "error", "warning", "information", "verbose"),
[int[]] $eventLogIds = @(),
[switch] $listen,
[switch] $listEventLogs,
[switch] $clearEventLogs,
[switch] $clearEventLogsOnGather,
[string] $command,
[int] $commandCount = 1,
[switch] $debugScript = $false,
[switch] $getUpdate,
[int] $jobThrottle = 10,
[switch] $nodynamicpath,
[switch] $rds
)
Set-StrictMode -Version Latest
$appendOutputFiles = $false
$debugLogsMax = 100
$errorActionPreference = "Continue"
$global:commandCountExecuted = 0
$global:debugLogsCount = 0
$global:eventLogLevelsQuery = $null
$global:eventLogIdsQuery = $null
$global:eventLogFiles = ![string]::IsNullOrEmpty($eventLogPath)
$global:eventLogNameSearchPattern = $eventLogNamePattern
$global:jobs = New-Object Collections.ArrayList
$global:machineRecords = @{}
$global:uploadDir = $uploadDir
$listenEventReadCount = 1000
$listenSleepMs = 100
$logFile = "event-log-manager-output.txt"
$global:logStream = $null
$global:logTimer = new-object Timers.Timer
$maxSortCount = 10000
$silent = $true
$startTimer = [DateTime]::Now
$startTime = [DateTime]::Now.ToString("yyyy-MM-dd-HH-mm-ss")
$updateUrl = "https://raw.githubusercontent.com/jagilber/powershellScripts/master/event-log-manager.ps1"
function main() {
$error.Clear()
# set upload directory
set-uploadDir
$logFile = "$(get-location)\$($logFile)"
log-info "starting $([DateTime]::Now.ToString()) $([Diagnostics.Process]::GetCurrentProcess().CommandLine)"
# log arguments
log-info $PSCmdlet.MyInvocation.Line;
log-arguments
# clean up old jobs
remove-jobs $silent
# some functions require admin
if ($clearEventLogs -or $enableDebugLogs -or $disableDebugLogs) {
runas-admin -force $true
if ($clearEventLogs) {
log-info "clearing event logs"
}
if ($enableDebugLogs) {
log-info "enabling debug event logs"
}
if ($disableDebugLogs) {
log-info "disabling debug event logs"
}
}
# check to see if running in admin prompt
runas-admin
# see if new (different) version of file
if ($getUpdate) {
get-update -updateUrl $updateUrl -destinationFile $MyInvocation.ScriptName
exit 0
}
# add local machine if empty
if ($machines.Count -lt 1) {
$machines += $env:COMPUTERNAME
}
elseif ($machines.Count -eq 1 -and $machines[0].Contains(",")) {
# when passing comma separated list of machines from bat, it does not get separated correctly
$machines = $machines[0].Split(",")
}
elseif ($machines.Count -eq 1 -and [IO.File]::Exists($machines)) {
# file passed in
$machines = [IO.File]::ReadAllLines($machines);
}
# setup for rds
if ($rds) {
log-info "setting up for rds environment"
$rdsPattern = "RDMS|RemoteApp|RemoteDesktop|Terminal|^System$|^Application$|User-Profile-Service" #CAPI|^Security$|VHDMP|"
if ([string]::IsNullOrEmpty($global:eventLogNameSearchPattern)) {
$global:eventLogNameSearchPattern = $rdsPattern
}
else {
$global:eventLogNameSearchPattern = "$($global:eventLogNameSearchPattern)|$($rdsPattern)"
}
}
# set default event log names if not specified
if (!$listEventLogs -and [string]::IsNullOrEmpty($global:eventLogNameSearchPattern)) {
$global:eventLogNameSearchPattern = "^Application$|^System$"
}
elseif ($listEventLogs -and [string]::IsNullOrEmpty($global:eventLogNameSearchPattern)) {
# just listing eventlogs and pattern not specified so show all
$global:eventLogNameSearchPattern = "."
}
elseif ($global:eventLogNameSearchPattern -eq "*") {
# using wildcard to use regex wildcard
$global:eventLogNameSearchPattern = ".*"
}
# set to local host if not specified
if ($machines.Length -lt 1) {
$machines = @($env:COMPUTERNAME)
}
# create xml query
[string]$global:eventLogLevelsQuery = build-eventLogLevels -eventLogLevels $eventLogLevels
[string]$global:eventLogIdsQuery = build-eventLogIds -eventLogIds $eventLogIds
# make sure start stop and other time range values were not all specified
if (![string]::IsNullOrEmpty($eventStartTime) -and ![string]::IsNullOrEmpty($eventStopTime) -and ($months + $days + $minutes -gt 0)) {
log-info "invalid parameter combination. cannot specify start and stop and other time range attributes in same command. exiting"
exit
}
# determine start time if specified else just search for today
if ($listen) {
$appendOutputFiles = $true
$eventStartTime = [DateTime]::Now
$eventStopTime = [DateTime]::MaxValue
}
if ([string]::IsNullOrEmpty($eventStartTime)) {
$origStartTime = ""
}
else {
$origStartTime = $eventStartTime
}
# determine start and stop times for xml query
$eventStartTime = configure-startTime -eventStartTime $eventStartTime `
-eventStopTime $eventStopTime `
-months $months `
-days $days `
-hours $hours `
-minutes $minutes
$eventStopTime = configure-stopTime -eventStarTime $origStartTime `
-eventStopTime $eventStopTime `
-months $months `
-days $days `
-hours $hours `
-minutes $minutes
try {
# process all machines
process-machines -machines $machines `
-eventStartTime $eventStartTime `
-eventStopTime $eventStopTime
}
catch {
log-info "main:exception $($error)"
}
finally {
# clean up
remove-jobs -silent $true
if ($listen -and $enableDebugLogs) {
$enableDebugLogs = $false
$disableDebugLogs = $true
$listen = $false
log-info "disabling debug logs that were enabled while listening"
# process all machines
process-machines -machines $machines `
-eventStartTime $eventStartTime `
-eventStopTime $eventStopTime
}
if ($global:debugLogsCount) {
show-debugWarning -count $global:debugLogsCount
}
if (!$listEventLogs -and @([IO.Directory]::GetFiles($global:uploadDir, "*.*", [IO.SearchOption]::AllDirectories)).Count -gt 0) {
if ($merge -or $displayMergedResults) {
merge-files
#start $global:uploadDir
}
log-info "files are located here: $($global:uploadDir)"
#tree /a /f $($global:uploadDir)
}
log-info "finished total seconds:$([DateTime]::Now.Subtract($startTimer).TotalSeconds.ToString("F2"))"
if ($global:logStream -ne $null) {
$global:logStream.Close()
}
$global:logTimer.Stop()
Unregister-Event logTimer -ErrorAction SilentlyContinue
}
}
function build-eventLogIds($eventLogIds) {
[Text.StringBuilder] $sb = new-object Text.StringBuilder
foreach ($eventLogId in $eventLogIds) {
[void]$sb.Append("EventID=$($eventLogId) or ")
}
return $sb.ToString().TrimEnd(" or ")
}
function build-eventLogLevels($eventLogLevels) {
[Text.StringBuilder] $sb = new-object Text.StringBuilder
foreach ($eventLogLevel in $eventLogLevels) {
switch ($eventLogLevel.ToLower()) {
"critical" { [void]$sb.Append("Level=1 or ") }
"error" { [void]$sb.Append("Level=2 or ") }
"warning" { [void]$sb.Append("Level=3 or ") }
"information" { [void]$sb.Append("Level=4 or Level=0 or ") }
"verbose" { [void]$sb.Append("Level=5 or ") }
}
}
return $sb.ToString().TrimEnd(" or ")
}
function configure-startTime( $eventStartTime, $eventStopTime, $months, $hours, $days, $minutes ) {
[DateTime] $time = new-object DateTime
[void][DateTime]::TryParse($eventStartTime, [ref] $time)
if ($time -eq [DateTime]::MinValue -and ![string]::IsNullOrEmpty($eventLogPath) -and ($months + $hours + $days + $minutes -eq 0)) {
# parsing existing evtx files so do not override $eventStartTime if it was not provided
[DateTime] $eventStartTime = $time
}
elseif ($time -eq [DateTime]::MinValue -and [string]::IsNullOrEmpty($eventStopTime) -and ($months + $hours + $days + $minutes -eq 0)) {
# default to just today
$time = [DateTime]::Now.Date
[DateTime] $eventStartTime = $time
}
elseif ($time -eq [DateTime]::MinValue -and [string]::IsNullOrEmpty($eventStopTime)) {
# subtract from current time
$time = [DateTime]::Now
[DateTime] $eventStartTime = $time.AddMonths( - $months).AddDays( - $days).AddHours( - $hours).AddMinutes( - $minutes)
}
else {
# offset should not be applied if $eventStartTime specified
[DateTime] $eventStartTime = $time
}
log-info "searching for events newer than: $($eventStartTime.ToString("yyyy-MM-ddTHH:mm:sszz"))"
return $eventStartTime
}
function configure-stopTime($eventStartTime, $eventStopTime, $months, $hours, $days, $minutes) {
[DateTime] $time = new-object DateTime
[void][DateTime]::TryParse($eventStopTime, [ref] $time)
if ([string]::IsNullOrEmpty($eventStartTime) -and $time -eq [DateTime]::MinValue -and ($months + $hours + $days + $minutes -gt 0)) {
# set to current and return
[DateTime] $eventStopTime = [DateTime]::Now
}
elseif ($time -eq [DateTime]::MinValue -and $months -eq 0 -and $hours -eq 0 -and $days -eq 0 -and $minutes -eq 0) {
[DateTime] $eventStopTime = [DateTime]::Now
}
elseif ($time -eq [DateTime]::MinValue) {
# subtract from current time
$time = [DateTime]::Now
[DateTime] $eventStopTime = $time.AddMonths( - $months).AddDays( - $days).AddHours( - $hours).AddMinutes( - $minutes)
}
else {
# offset should not be applied if $eventStopTime specified
[DateTime] $eventStopTime = $time
}
log-info "searching for events older than: $($eventStopTime.ToString("yyyy-MM-ddTHH:mm:sszz"))"
return $eventStopTime
}
function dump-events( $eventLogNames, [string] $machine, [DateTime] $eventStartTime, [DateTime] $eventStopTime) {
$newEvents = New-Object Collections.ArrayList
$listenJobItem = @{}
$preader = $null
# build query string from ids and levels
if (![string]::IsNullOrEmpty($global:eventLogLevelsQuery) -and ![string]::IsNullOrEmpty($global:eventLogIdsQuery)) {
$eventQuery = "($($global:eventLogLevelsQuery)) and ($($global:eventLogIdsQuery)) and "
}
elseif (![string]::IsNullOrEmpty($global:eventLogLevelsQuery)) {
$eventQuery = "($($global:eventLogLevelsQuery)) and "
}
elseif (![string]::IsNullOrEmpty($global:eventLogIdsQuery)) {
$eventQuery = "($($global:eventLogIdsQuery)) and "
}
# used to peek at events
$psession = New-Object Diagnostics.Eventing.Reader.EventLogSession ($machine)
# loop through each log
foreach ($eventLogName in $eventLogNames) {
$outputCsv = [string]::Empty
$recordid = ($global:machineRecords[$machine])[$eventLogName]
$queryString = "<QueryList>
<Query Id=`"0`" Path=`"$($eventLogName)`">
<Select Path=`"$($eventLogName)`">*[System[$($eventQuery)" `
+ "TimeCreated[@SystemTime >=`'$($eventStartTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"))`' " `
+ "and @SystemTime <=`'$($eventStopTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ"))`']]]</Select>
</Query>
</QueryList>"
log-info -debugOnly -data $queryString
try {
$pathType = $null
# peek to see if any records, if so start job
if (!$global:eventLogFiles) {
$pathType = [Diagnostics.Eventing.Reader.PathType]::LogName
}
else {
$pathType = [Diagnostics.Eventing.Reader.PathType]::FilePath
}
log-info -debugOnly -data ($psession.GetLogInformation($eventLogName, $pathType) | Format-List * | out-string)
$pquery = New-Object Diagnostics.Eventing.Reader.EventLogQuery ($eventLogName, $pathType, $queryString)
$pquery.Session = $psession
$preader = New-Object Diagnostics.Eventing.Reader.EventLogReader $pquery
# create csv file name
$cleanName = $eventLogName.Replace("/", "-").Replace(" ", "-")
if (!$global:eventLogFiles) {
$outputCsv = ("$($global:uploadDir)\$($machine)-$($cleanName).csv")
}
else {
$outputCsv = ("$($global:uploadDir)\$([IO.Path]::GetFileNameWithoutExtension($cleanName)).csv")
}
if (!$appendOutputFiles -and (test-path $outputCsv)) {
log-info "removing existing file: $($outputCsv)"
Remove-Item -Path $outputCsv -Force
}
if ($listen) {
if (!$listenJobItem -or $listenJobItem.Keys.Count -eq 0) {
$listenJobItem = @{}
$listenJobItem.Machine = $machine
$listenJobItem.EventLogItems = @{}
}
$listenJobItem.EventLogItems.Add($eventLogName, @{
EventQuery = $eventQuery
QueryString = $queryString
OutputCsv = $outputCsv
RecordId = 0
}
)
}
$event = $preader.ReadEvent()
if ($event -eq $null) {
continue
}
if ($recordid -eq $event.RecordId) {
#sometimes record id's come back as 0 causing dupes
$recordid++
}
$oldrecordid = ($global:machineRecords[$machine])[$eventLogName]
$recordid = [Math]::Max($recordid, $event.RecordId)
log-info "dump-events:machine: $($machine) event log name: $eventLogName old index: $($oldRecordid) new index: $($recordId)" -debugOnly
($global:machineRecords[$machine])[$eventLogName] = $recordid
}
catch {
log-info "FAIL:$($eventLogName): $($Error)" -debugOnly
[void]$error.Clear()
continue
}
if (!$listen) {
$job = start-exportJob -machine $machine `
-eventLogName $eventLogName `
-queryString $queryString `
-outputCsv $outputCsv
if ($job -ne $null) {
log-info "job $($job.id) started for eventlog: $($eventLogName)"
$global:jobs.Add($job)
}
}
}
if ($listenJobItem -and $listenJobItem.Count -gt 0) {
$job = start-listenJob -jobItem $listenJobItem
}
$preader.CancelReading()
$preader.Dispose()
$psession.CancelCurrentOperations()
$psession.Dispose()
return , $newEvents
}
function enable-logs($eventLogNames, $machine) {
log-info "enabling / disabling logs on $($machine)."
[Text.StringBuilder] $sb = new-object Text.StringBuilder
$debugLogsEnabled = New-Object Collections.ArrayList
[void]$sb.Appendline("event logs:")
try {
foreach ($eventLogName in $eventLogNames) {
$error.clear()
try {
$session = New-Object Diagnostics.Eventing.Reader.EventLogSession ($machine)
$eventLog = New-Object Diagnostics.Eventing.Reader.EventLogConfiguration ($eventLogName, $session)
}
catch {
log-info "warning:unable to open eventlog $($eventLogName) $($error)"
$error.clear()
}
if ($clearEventLogs) {
[void]$sb.AppendLine("clearing event log: $($eventLogName)")
if ($eventLog.IsEnabled -and !$eventLog.IsClassicLog) {
$eventLog.IsEnabled = $false
$eventLog.SaveChanges()
$eventLog.Dispose()
$session.ClearLog($eventLogName)
$eventLog = New-Object Diagnostics.Eventing.Reader.EventLogConfiguration ($eventLogName, $session)
$eventLog.IsEnabled = $true
$eventLog.SaveChanges()
}
elseif ($eventLog.IsClassicLog) {
$session.ClearLog($eventLogName)
}
}
if ($enableDebugLogs -and $eventLog.IsEnabled -eq $false) {
if ($VerbosePreference -ine "SilentlyContinue" -or $listEventLogs) {
[void]$sb.AppendLine("enabling debug log for $($eventLog.LogName) $($eventLog.LogMode)")
}
$eventLog.IsEnabled = $true
$eventLog.SaveChanges()
$global:debugLogsCount++
}
if ($disableDebugLogs -and $eventLog.IsEnabled -eq $true -and ($eventLog.LogType -ieq "Analytic" -or $eventLog.LogType -ieq "Debug")) {
if ($VerbosePreference -ine "SilentlyContinue" -or $listEventLogs) {
[void]$sb.AppendLine("disabling debug log for $($eventLog.LogName) $($eventLog.LogMode)")
}
$eventLog.IsEnabled = $false
$eventLog.SaveChanges()
$global:debugLogsCount--
if ($debugLogsEnabled.Contains($eventLog.LogName)) {
$debugLogsEnabled.Remove($eventLog.LogName)
}
}
if ($eventLog.LogType -ieq "Analytic" -or $eventLog.LogType -ieq "Debug") {
if ($eventLog.IsEnabled -eq $true) {
[void]$sb.AppendLine("$($eventLog.LogName) $($eventLog.LogMode): ENABLED")
$debugLogsEnabled.Add($eventLog.LogName)
if ($debugLogsMax -le $debugLogsEnabled.Count) {
log-info "Error: too many debug logs enabled ($($debugLogsMax))."
log-info "Error: this can cause system performance / stability issues as well as inability to boot!"
log-info "Error: rerun script again with these switches: .\event-log-manager.ps1 -listeventlogs -disableDebugLogs"
log-info "Error: this will disable all debug logs."
log-info "Warning: exiting script."
exit 1
}
}
else {
[void]$sb.AppendLine("$($eventLog.LogName) $($eventLog.LogMode): DISABLED")
}
}
else {
[void]$sb.AppendLine("$($eventLog.LogName)")
}
}
log-info $sb.ToString() -nocolor
log-info "-----------------------------------------"
if ($debugLogsEnabled.Count -gt 0) {
foreach ($eventLogName in $debugLogsEnabled) {
log-info $eventLogName
}
show-debugWarning -count $debugLogsEnabled.Count
}
return $true
}
catch {
log-info "enable logs exception: $($error | out-string)"
$error.Clear()
return $false
}
}
function filter-eventLogs($eventLogPattern, $machine, $eventLogPath) {
$filteredEventLogs = New-Object Collections.ArrayList
try {
if (!$global:eventLogFiles) {
# query eventlog session
$session = New-Object Diagnostics.Eventing.Reader.EventLogSession ($machine)
$eventLogNames = $session.GetLogNames()
}
else {
if ([IO.File]::Exists($eventLogPath)) {
$eventLogNames = @($eventLogPath)
}
else {
# query eventlog path
$eventLogNames = [IO.Directory]::GetFiles($eventLogPath, "*.evt*", [IO.SearchOption]::TopDirectoryOnly)
}
}
[Text.StringBuilder] $sb = new-object Text.StringBuilder
foreach ($eventLogName in $eventLogNames) {
if (![regex]::IsMatch($eventLogName, $eventLogPattern , [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) {
continue
}
[void]$filteredEventLogs.Add($eventLogName)
[void]$sb.Appendline($eventLogName)
}
[void]$sb.AppendLine("filtered logs count: $($filteredEventLogs.Count)")
log-info $sb.ToString()
return $filteredEventLogs
}
catch {
log-info "exception reading event log names from $($machine): $($error)"
$error.Clear()
return $null
}
}
function get-update($updateUrl, $destinationFile) {
log-info "get-update:checking for updated script: $($updateUrl)"
$file = ""
$git = $null
try {
$git = Invoke-RestMethod -Method Get -Uri $updateUrl
# git may not have carriage return
if ([regex]::Matches($git, "`r").Count -eq 0) {
$git = [regex]::Replace($git, "`n", "`r`n")
}
if ([IO.File]::Exists($destinationFile)) {
$file = [IO.File]::ReadAllText($destinationFile)
}
if (([string]::Compare($git, $file) -ne 0)) {
log-info "copying script $($destinationFile)"
[IO.File]::WriteAllText($destinationFile, $git)
return $true
}
else {
log-info "script is up to date"
}
return $false
}
catch [System.Exception] {
log-info "get-update:exception: $($error)"
$error.Clear()
return $false
}
}
function listen-forEvents() {
$unsortedEvents = New-Object Collections.ArrayList
$sortedEvents = New-Object Collections.ArrayList
$newEvents = New-Object Collections.ArrayList
try {
while ($listen) {
# ensure sort by keeping two sets and comparing new to old then displaying old
[void]$sortedEvents.Clear()
$sortedEvents = $unsortedEvents.Clone()
[void]$unsortedEvents.Clear()
$color = $true
# get events from jobs
$newEvents = @(get-job * | Receive-Job)
# run command if eventtracepattern or eventlogids were provided and command provided
# will launch separate process
if ($newEvents.Count -gt 0 `
-and $commandCount -gt $global:commandCountExecuted `
-and ![string]::IsNullOrEmpty($command) `
-and (![string]::IsNullOrEmpty($eventTracePattern) -or $eventLogIds.Count -gt 0))
{
log-info "information: starting command cmd.exe /c start $($command) `"$($newEvents[0] | Out-String)`""
Start-Process -FilePath "cmd.exe" -ArgumentList "/c start $($command) `"$($newEvents[0] | Out-String)`""
$global:commandCountExecuted++
log-info "information: finished starting command. number of commands started $($global:commandCountExecuted)"
if ($global:commandCountExecuted -eq $commandCountExecuted) {
log-info "Warning: no more command instances will be started on new matches. To modify use -commandCountExecuted argument"
}
}
if ($debugScript) {
log-info (get-job).Debug | Format-List * | out-string
}
if ($newEvents.Count -gt 0) {
[void]$unsortedEvents.AddRange(@($newEvents | sort-object))
}
if ($unsortedEvents.Count -gt $maxSortCount) {
# too many to sort, just display / save
[void]$sortedEvents.AddRange($unsortedEvents)
$unsortedEvents.Clear()
log-info "Warning:listen: unsorted count too high, skipping sort" -debugOnly
if ($sortedEvents.Count -gt 0) {
foreach ($sortedEvent in $sortedEvents) {
log-info $sortedEvent -nocolor
}
}
$sortedEvents.Clear()
if ($unsortedEvents.Count -gt 0) {
foreach ($sortedEvent in $unsortedEvents) {
log-info $sortedEvent -nocolor
}
}
$unsortedEvents.Clear()
}
elseif ($unsortedEvents.Count -gt 0 -and $sortedEvents.Count -gt 0) {
$result = [DateTime]::MinValue
$trace = $sortedEvents[$sortedEvents.Count - 1]
# date and time are at start of string separated by commas.
# search for second comma splitting date and time from trace message to extract just date and time
$traceDate = $trace.Substring(0, $trace.IndexOf(",", 11))
if ([DateTime]::TryParse($traceDate, [ref] $result)) {
$straceDate = $result
}
for ($i = 0; $i -lt $unsortedEvents.Count; $i++) {
$trace = $unsortedEvents[$i]
$traceDate = $trace.Substring(0, $trace.IndexOf(",", 11))
if ([DateTime]::TryParse($traceDate, [ref] $result)) {
$utraceDate = $result
}
if ($utraceDate -gt $straceDate) {
log-info "moving trace to unsorted" -debugOnly
# move ones earlier than max of unsorted from sorted to unsorted keep timeline right
[void]$sortedEvents.Insert(0, $unsortedEvents[0])
[void]$unsortedEvents.RemoveAt(0)
}
}
}
if ($sortedEvents.Count -gt 0) {
foreach ($sortedEvent in $sortedEvents | Sort-Object) {
log-info $sortedEvent
write-host "------------------------------------------"
}
}
log-info "listen: unsorted count:$($unsortedEvents.Count) sorted count: $($sortedEvents.Count)" -debugOnly
Start-Sleep -Milliseconds ($listenSleepMs * 2)
}
}
catch {
log-info "listen:exception: $($error)"
}
}
function log-arguments() {
log-info "clearEventLogs:$($clearEventLogs)"
log-info "clearEventLogsOnGather:$($clearEventLogsOnGather)"
log-info "command:$($command)"
log-info "commandCount:$($commandCount)"
log-info "days:$($days)"
log-info "debugScript:$($debugScript)"
log-info "disableDebugLogs:$($disableDebugLogs)"
log-info "displayMergedResults:$($displayMergedResults)"
log-info "enableDebugLogs:$($enableDebugLogs)"
log-info "eventDetails:$($eventDetails)"
log-info "eventDetailsFormatted:$($eventDetailsFormatted)"
log-info "eventLogLevels:$($eventLogLevels -join ",")"
log-info "eventLogIds:$($eventLogIds -join ",")"
log-info "eventLogNamePattern:$($eventLogNamePattern)"
log-info "eventLogPath:$($eventLogPath)"
log-info "eventStartTime:$($eventStartTime)"
log-info "eventStopTime:$($eventStopTime)"
log-info "eventTracePattern:$($eventTracePattern)"
log-info "getUpdate:$($getUpdate)"
log-info "hours:$($hours)"
log-info "listen:$($listen)"
log-info "listEventLogs:$($listEventLogs)"
log-info "logFile:$($logFile)"
log-info "machines:$($machines -join ",")"
log-info "minutes:$($minutes)"
log-info "merge:$($merge)"
log-info "months:$($months)"
log-info "nodynamicpath:$($nodynamicpath)"
log-info "rds:$($rds)"
log-info "uploadDir:$($global:uploadDir)"
}
function log-info($data, [switch] $nocolor = $false, [switch] $debugOnly = $false) {
try {
if ($debugOnly -and !$debugScript) {
return
}
if (!$data) {
return
}
$foregroundColor = "White"
if (!$nocolor) {
if ($data.ToString().ToLower().Contains("error")) {
$foregroundColor = "Red"
}