Tuesday, September 11, 2012

Less Thrashing; Better Queries (Part V)

# Updated: 7:01 AM 1/19/2014  -RMF

# Using [System.Diagnostics.EventLog] for Powershell 3.0 Beta
# Code
# Clearing variable types 
rv -ea 0 i;
rv -ea 0 var
$var=@("a","b","c","d","e"); foreach ($i in $var) {rv -ea 0 $i}
 #Creating $a specific to the 'GetEventLogs()' 
 # method for [System.Diagnostics.EventLog]
 $a=[System.Diagnostics.EventLog]::GetEventLogs()
 $a | gm -s
 # List the event logs
 $a

 # Creating $a as generic to the .NET class; Querying active
 # Eventlog for a local(or remote?)computer name:
 $a=[System.Diagnostics.EventLog]
 $a::GetEventLogs("rmfvpc")
 $a::GetEventLogs("rmfvpc") | gm -s

 # Creating $B as the result of mahine specific
 #'GetEventLogs()' query
 $b=$a::GetEventLogs("rmfvpc")
 $b | gm -s
 $b | gm -f

 # Using $B to get a specific method for a specific log (e.g. 
 # Array[10]) for specific configuration method (e.g. 
 # 'get_OverflowAction()')
 $b[10]
 $b[10].get_OverflowAction()

 # Choose the Security Log
 $C = $B | Where Log -eq Security

 # This retrieves all Entries before returning the first index.
 $c[0].get_Entries()[0]
 $c[0].get_Entries()[0] | gm -f

 #Returns select entries and then select EventIDs for such.
 $c[0].get_Entries()[100..110]
 $c[0].get_Entries()[100..110]
 $c[0].get_Entries()[100..110].get_EventID()

 # Number of Events Logs; Number of total events for a 
 # specific Event Log.
 $c[0].count
 $c[0].Entries.count

 # Returns First and Last Events
 $lc = $($c[0].Entries.count - 1) 
 $c[0].get_Entries()[0,$($c[0].Entries.count - $lc)]

 # Creates a DateTime variable;Returns number of days 
 # between first and last events
 ($c[0].get_Entries()[0,$lc]).TimeGenerated
 $TG=($c[0].get_Entries()[0,$lc]).TimeGenerated
 $TG  | gm -s
 $TG[1]-$TG[0]
 ($TG[1]-$TG[0]).Days

 # Returns select sorted information last 1000 entries
 $d=($c[0].get_Entries())[0..999]| Select EventID,Message
 $d.count
 $d[0..9] | ft -auto -wrap
 $d | group -property EventID -noelement | sort -desc -property Count
 $e= ($d | group -property Message -noelement | sort -desc -property Count)
 $e.count
 $e[0..9] | ft -auto -wrap



# Results
PS C:\>  $a=[System.Diagnostics.EventLog]::GetEventLogs()
PS C:\>  $a | gm -s


   TypeName: System.Diagnostics.EventLog

Name                  MemberType Definition
----                  ---------- ----------
CreateEventSource     Method     static void CreateEventSource(string source, string logName), static void CreateEventSource(string source, string logName, string m...
Delete                Method     static void Delete(string logName), static void Delete(string logName, string machineName)
DeleteEventSource     Method     static void DeleteEventSource(string source), static void DeleteEventSource(string source, string machineName)
Equals                Method     static bool Equals(System.Object objA, System.Object objB)
Exists                Method     static bool Exists(string logName), static bool Exists(string logName, string machineName)
GetEventLogs          Method     static System.Diagnostics.EventLog[] GetEventLogs(), static System.Diagnostics.EventLog[] GetEventLogs(string machineName)
LogNameFromSourceName Method     static string LogNameFromSourceName(string source, string machineName)
ReferenceEquals       Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
SourceExists          Method     static bool SourceExists(string source), static bool SourceExists(string source, string machineName)
WriteEntry            Method     static void WriteEntry(string source, string message), static void WriteEntry(string source, string message, System.Diagnostics.Eve...
WriteEvent            Method     static void WriteEvent(string source, System.Diagnostics.EventInstance instance, Params System.Object[] values), static void WriteE...
Site                  Property   System.ComponentModel.ISite Site {get;set;}


PS C:\>  $a

  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  20,480      0 OverwriteAsNeeded      30,331 Application
     512      7 OverwriteOlder             68 EstablishedTCPConnections
     512      7 OverwriteOlder             22 gwmi_diff
  20,480      0 OverwriteAsNeeded           0 HardwareEvents
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
   8,192      0 OverwriteAsNeeded         278 Media Center
     512      7 OverwriteOlder          2,184 OasisLog
  16,384      0 OverwriteAsNeeded           0 ODiag
  16,384      0 OverwriteAsNeeded          37 OSession
 600,576     -1 DoNotOverwrite      1,018,834 Security
  25,600      0 OverwriteAsNeeded           1 SmartWi
  20,480      0 OverwriteAsNeeded      34,862 System
  15,360      0 OverwriteAsNeeded      18,289 Windows PowerShell


PS C:\>  $a=[System.Diagnostics.EventLog]
PS C:\>  $a::GetEventLogs("rmfvpc")

  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  20,480      0 OverwriteAsNeeded      30,331 Application
     512      7 OverwriteOlder             68 EstablishedTCPConnections
     512      7 OverwriteOlder             22 gwmi_diff
  20,480      0 OverwriteAsNeeded           0 HardwareEvents
     512      7 OverwriteOlder              0 Internet Explorer
  20,480      0 OverwriteAsNeeded           0 Key Management Service
   8,192      0 OverwriteAsNeeded         278 Media Center
     512      7 OverwriteOlder          2,184 OasisLog
  16,384      0 OverwriteAsNeeded           0 ODiag
  16,384      0 OverwriteAsNeeded          37 OSession
 600,576     -1 DoNotOverwrite      1,018,834 Security
  25,600      0 OverwriteAsNeeded           1 SmartWi
  20,480      0 OverwriteAsNeeded      34,862 System
  15,360      0 OverwriteAsNeeded      18,289 Windows PowerShell


PS C:\>  $a::GetEventLogs("rmfvpc") | gm -s


   TypeName: System.Diagnostics.EventLog

Name                  MemberType Definition
----                  ---------- ----------
CreateEventSource     Method     static void CreateEventSource(string source, string logName), static void CreateEventSource(string source, string logName, string m...
Delete                Method     static void Delete(string logName), static void Delete(string logName, string machineName)
DeleteEventSource     Method     static void DeleteEventSource(string source), static void DeleteEventSource(string source, string machineName)
Equals                Method     static bool Equals(System.Object objA, System.Object objB)
Exists                Method     static bool Exists(string logName), static bool Exists(string logName, string machineName)
GetEventLogs          Method     static System.Diagnostics.EventLog[] GetEventLogs(), static System.Diagnostics.EventLog[] GetEventLogs(string machineName)
LogNameFromSourceName Method     static string LogNameFromSourceName(string source, string machineName)
ReferenceEquals       Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
SourceExists          Method     static bool SourceExists(string source), static bool SourceExists(string source, string machineName)
WriteEntry            Method     static void WriteEntry(string source, string message), static void WriteEntry(string source, string message, System.Diagnostics.Eve...
WriteEvent            Method     static void WriteEvent(string source, System.Diagnostics.EventInstance instance, Params System.Object[] values), static void WriteE...
Site                  Property   System.ComponentModel.ISite Site {get;set;}


PS C:\>  $b=$a::GetEventLogs("rmfvpc")
PS C:\>  $b | gm -f


   TypeName: System.Diagnostics.EventLog

Name                      MemberType   Definition
----                      ----------   ----------
pstypenames               CodeProperty System.Collections.ObjectModel.Collection`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c...
Disposed                  Event        System.EventHandler Disposed(System.Object, System.EventArgs)
EntryWritten              Event        System.Diagnostics.EntryWrittenEventHandler EntryWritten(System.Object, System.Diagnostics.EntryWrittenEventArgs)
psadapted                 MemberSet    psadapted {Entries, LogDisplayName, Log, MachineName, MaximumKilobytes, OverflowAction, MinimumRetentionDays, EnableRaisingEv...
psbase                    MemberSet    psbase {Entries, LogDisplayName, Log, MachineName, MaximumKilobytes, OverflowAction, MinimumRetentionDays, EnableRaisingEvent...
psextended                MemberSet    psextended {}
psobject                  MemberSet    psobject {Members, Properties, Methods, ImmediateBaseObject, BaseObject, TypeNames, get_Members, get_Properties, get_Methods,...
add_Disposed              Method       void add_Disposed(System.EventHandler value), void IComponent.add_Disposed(System.EventHandler value)
add_EntryWritten          Method       void add_EntryWritten(System.Diagnostics.EntryWrittenEventHandler value)
BeginInit                 Method       void BeginInit(), void ISupportInitialize.BeginInit()
Clear                     Method       void Clear()
Close                     Method       void Close()
CreateObjRef              Method       System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                   Method       void Dispose(), void IDisposable.Dispose()
EndInit                   Method       void EndInit(), void ISupportInitialize.EndInit()
Equals                    Method       bool Equals(System.Object obj)
GetHashCode               Method       int GetHashCode()
GetLifetimeService        Method       System.Object GetLifetimeService()
GetType                   Method       type GetType()
get_Container             Method       System.ComponentModel.IContainer get_Container()
get_EnableRaisingEvents   Method       bool get_EnableRaisingEvents()
get_Entries               Method       System.Diagnostics.EventLogEntryCollection get_Entries()
get_Log                   Method       string get_Log()
get_LogDisplayName        Method       string get_LogDisplayName()
get_MachineName           Method       string get_MachineName()
get_MaximumKilobytes      Method       long get_MaximumKilobytes()
get_MinimumRetentionDays  Method       int get_MinimumRetentionDays()
get_OverflowAction        Method       System.Diagnostics.OverflowAction get_OverflowAction()
get_Site                  Method       System.ComponentModel.ISite get_Site(), System.ComponentModel.ISite IComponent.get_Site()
get_Source                Method       string get_Source()
get_SynchronizingObject   Method       System.ComponentModel.ISynchronizeInvoke get_SynchronizingObject()
InitializeLifetimeService Method       System.Object InitializeLifetimeService()
ModifyOverflowPolicy      Method       void ModifyOverflowPolicy(System.Diagnostics.OverflowAction action, int retentionDays)
RegisterDisplayName       Method       void RegisterDisplayName(string resourceFile, long resourceId)
remove_Disposed           Method       void remove_Disposed(System.EventHandler value), void IComponent.remove_Disposed(System.EventHandler value)
remove_EntryWritten       Method       void remove_EntryWritten(System.Diagnostics.EntryWrittenEventHandler value)
set_EnableRaisingEvents   Method       void set_EnableRaisingEvents(bool value)
set_Log                   Method       void set_Log(string value)
set_MachineName           Method       void set_MachineName(string value)
set_MaximumKilobytes      Method       void set_MaximumKilobytes(long value)
set_Site                  Method       void set_Site(System.ComponentModel.ISite value), void IComponent.set_Site(System.ComponentModel.ISite value)
set_Source                Method       void set_Source(string value)
set_SynchronizingObject   Method       void set_SynchronizingObject(System.ComponentModel.ISynchronizeInvoke value)
ToString                  Method       string ToString()
WriteEntry                Method       void WriteEntry(string message), void WriteEntry(string message, System.Diagnostics.EventLogEntryType type), void WriteEntry(...
WriteEvent                Method       void WriteEvent(System.Diagnostics.EventInstance instance, Params System.Object[] values), void WriteEvent(System.Diagnostics...
Container                 Property     System.ComponentModel.IContainer Container {get;}
EnableRaisingEvents       Property     bool EnableRaisingEvents {get;set;}
Entries                   Property     System.Diagnostics.EventLogEntryCollection Entries {get;}
Log                       Property     string Log {get;set;}
LogDisplayName            Property     string LogDisplayName {get;}
MachineName               Property     string MachineName {get;set;}
MaximumKilobytes          Property     long MaximumKilobytes {get;set;}
MinimumRetentionDays      Property     int MinimumRetentionDays {get;}
OverflowAction            Property     System.Diagnostics.OverflowAction OverflowAction {get;}
Site                      Property     System.ComponentModel.ISite Site {get;set;}
Source                    Property     string Source {get;set;}
SynchronizingObject       Property     System.ComponentModel.ISynchronizeInvoke SynchronizingObject {get;set;}


PS C:\>  $b[10]

  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
 600,576     -1 DoNotOverwrite      1,018,834 Security


PS C:\>  $b[10].get_OverflowAction()
DoNotOverwrite
PS C:\>
PS C:\>  $b[0]

  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  20,480      0 OverwriteAsNeeded      30,331 Application


PS C:\>  $b[0].get_Entries()[0]

   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
    2498 Jul 04 13:14  Error       SideBySide             3238068257 Activation context generation failed for "C:\Windows\Installer\{67E03279-F703-408F-B4BF-46B5FC8...

PS C:\> $b[0].get_Entries()[100..110]

   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
    2598 Oct 10 17:35  Information VCFw                            0 The description for Event ID '0' in Source 'VCFw' cannot be found.  The local computer may not ...
    2599 Oct 10 17:35  Information SecurityCenter                  1 The Windows Security Center Service has started.
    2600 Oct 10 17:35  Information Microsoft-Windows...         1001 Performance counters for the WmiApRpl (WmiApRpl) service were removed successfully. The Record ...
    2601 Oct 10 17:35  Information Microsoft-Windows...         1000 Performance counters for the WmiApRpl (WmiApRpl) service were loaded successfully. The Record D...
    2602 Oct 10 17:38  0           Software Protecti...   1073742727 The Software Protection service has stopped....
    2603 Oct 10 17:39  Information MSSQL$DDNI             1073758961 Starting up database 'Oasis'.
    2604 Oct 10 17:48  Error       Google Update                  20 The description for Event ID '20' in Source 'Google Update' cannot be found.  The local compute...
    2605 Oct 10 17:50  Information Windows Error Rep...         1001 Fault bucket , type 0...
    2606 Oct 10 17:55  Information Windows Error Rep...         1001 Fault bucket , type 0...
    2607 Oct 10 18:01  Error       Google Update                  20 The description for Event ID '20' in Source 'Google Update' cannot be found.  The local compute...
    2608 Oct 10 18:01  0           Microsoft-Windows...          258 The disk defragmenter successfully completed analysis on Windows (C:)


PS C:\> $b[0].get_Entries()[100..110].EventID
0
1
1001
1000
903
17137
20
1001
1001
20
258

PS C:\> $b[0].get_Entries()[100..110].get_EventID()
0
1
1001
1000
903
17137
20
1001
1001
20
258

PS C:\>  $b[0].Entries.count
30331

PS C:\>  $b[0].get_Entries()[0,30324]

   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
    2498 Jul 04 13:14  Error       SideBySide             3238068257 Activation context generation failed for "C:\Windows\Installer\{67E03279-F703-408F-B4BF-46B5FC8...
   32822 Sep 11 09:12  Information gusvc                           0 The description for Event ID '0' in Source 'gusvc' cannot be found.  The local computer may not...


PS C:\>  $b[0].get_Entries()[0,30324] | gm


   TypeName: System.Diagnostics.EventLogEntry

Name                      MemberType     Definition
----                      ----------     ----------
Disposed                  Event          System.EventHandler Disposed(System.Object, System.EventArgs)
CreateObjRef              Method         System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                   Method         void Dispose(), void IDisposable.Dispose()
Equals                    Method         bool Equals(System.Diagnostics.EventLogEntry otherEntry), bool Equals(System.Object obj)
GetHashCode               Method         int GetHashCode()
GetLifetimeService        Method         System.Object GetLifetimeService()
GetObjectData             Method         void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.Streamin...
GetType                   Method         type GetType()
InitializeLifetimeService Method         System.Object InitializeLifetimeService()
ToString                  Method         string ToString()
Category                  Property       string Category {get;}
CategoryNumber            Property       int16 CategoryNumber {get;}
Container                 Property       System.ComponentModel.IContainer Container {get;}
Data                      Property       byte[] Data {get;}
EntryType                 Property       System.Diagnostics.EventLogEntryType EntryType {get;}
Index                     Property       int Index {get;}
InstanceId                Property       long InstanceId {get;}
MachineName               Property       string MachineName {get;}
Message                   Property       string Message {get;}
ReplacementStrings        Property       string[] ReplacementStrings {get;}
Site                      Property       System.ComponentModel.ISite Site {get;set;}
Source                    Property       string Source {get;}
TimeGenerated             Property       datetime TimeGenerated {get;}
TimeWritten               Property       datetime TimeWritten {get;}
UserName                  Property       string UserName {get;}
EventID                   ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}


PS C:\>  ($b[0].get_Entries()[0,30324]).TimeGenerated

Sunday, July 04, 2010 1:14:23 PM
Tuesday, September 11, 2012 9:12:48 AM


PS C:\> $TG=($b[0].get_Entries()[0,30324]).TimeGenerated
PS C:\> $TG  | gm -s


   TypeName: System.DateTime

Name            MemberType Definition
----            ---------- ----------
Compare         Method     static int Compare(datetime t1, datetime t2)
DaysInMonth     Method     static int DaysInMonth(int year, int month)
Equals          Method     static bool Equals(datetime t1, datetime t2), static bool Equals(System.Object objA, System.Object objB)
FromBinary      Method     static datetime FromBinary(long dateData)
FromFileTime    Method     static datetime FromFileTime(long fileTime)
FromFileTimeUtc Method     static datetime FromFileTimeUtc(long fileTime)
FromOADate      Method     static datetime FromOADate(double d)
IsLeapYear      Method     static bool IsLeapYear(int year)
Parse           Method     static datetime Parse(string s), static datetime Parse(string s, System.IFormatProvider provider), static datetime Parse(string s, System...
ParseExact      Method     static datetime ParseExact(string s, string format, System.IFormatProvider provider), static datetime ParseExact(string s, string format,...
ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
SpecifyKind     Method     static datetime SpecifyKind(datetime value, System.DateTimeKind kind)
TryParse        Method     static bool TryParse(string s, [ref] datetime result), static bool TryParse(string s, System.IFormatProvider provider, System.Globalizati...
TryParseExact   Method     static bool TryParseExact(string s, string format, System.IFormatProvider provider, System.Globalization.DateTimeStyles style, [ref] date...
MaxValue        Property   static datetime MaxValue {get;}
MinValue        Property   static datetime MinValue {get;}
Now             Property   datetime Now {get;}
Today           Property   datetime Today {get;}
UtcNow          Property   datetime UtcNow {get;}  

PS C:\>  $TG[1]-$TG[0]


Days              : 799
Hours             : 19
Minutes           : 58
Seconds           : 25
Milliseconds      : 0
Ticks             : 691055050000000
TotalDays         : 799.832233796296
TotalHours        : 19195.9736111111
TotalMinutes      : 1151758.41666667
TotalSeconds      : 69105505
TotalMilliseconds : 69105505000



PS C:\>  ($TG[1]-$TG[0]).Days
799

PS C:\> ($b[0].get_Entries().EventID) | group -noelement | sort -desc -property Count

Count Name
----- ----
 5017 0
 2780 257
 2310 1035
 1079 17137
  917 1001
  885 1040
  882 1042
  858 4107
  798 8224
  776 10000
  765 10001
  644 1033
  560 11728
  475 11707
  470 1904
  420 1
  409 8194
  387 1003
  253 301
  249 1000
  244 1036
  244 1022
  227 26048
  216 9666
  205 102
  199 6000
  195 900
  195 902
  195 1066
  192 903
  188 3454
  175 17403
  172 1002
  166 35
  133 1531
  133 4625
  131 5617
  131 5615
  128 2000
  127 4101
  125 3407
  125 258
  124 300
  124 302
  124 3406
  120 17401
  119 17199
  119 26018
  119 3408
  119 17126
  119 26037
  119 17111
  119 15268
  119 17162
  119 17110
  119 18496
  119 17101
...

PS C:\>  $d=($b[0].get_Entries())| Select EventID,Message
PS C:\>  $d.count
30330

PS C:\> $d[0..10] | ft -auto -wrap

EventID Message
------- -------
     33 Activation context generation failed for "C:\Windows\Installer\{67E03279-F703-408F-B4BF-46B5FC8D70CD}\WksCal.exe".
        Dependent Assembly msadctls,processorArchitecture="x86",type="win32",version="1.0.1801.0" could not be found.
        Please use sxstrace.exe for detailed diagnosis.
     33 Activation context generation failed for "C:\Windows\Installer\{67E03279-F703-408F-B4BF-46B5FC8D70CD}\wksdb.exe".
        Dependent Assembly msadctls,processorArchitecture="x86",type="win32",version="1.0.1801.0" could not be found.
        Please use sxstrace.exe for detailed diagnosis.
     33 Activation context generation failed for "C:\Windows\Installer\{67E03279-F703-408F-B4BF-46B5FC8D70CD}\wksss.exe".
        Dependent Assembly msadctls,processorArchitecture="x86",type="win32",version="1.0.1801.0" could not be found.
        Please use sxstrace.exe for detailed diagnosis.
     33 Activation context generation failed for "C:\Windows\Installer\{67E03279-F703-408F-B4BF-46B5FC8D70CD}\WksWP.exe".
        Dependent Assembly msadctls,processorArchitecture="x86",type="win32",version="1.0.1801.0" could not be found.
        Please use sxstrace.exe for detailed diagnosis.
...

PS C:\>  $d | group -property EventID -noelement | sort -desc -property Count

Count Name
----- ----
 5017 0
 2780 257
 2310 1035
 1079 17137
  917 1001
  885 1040
  882 1042
  858 4107
  797 8224
  776 10000
  765 10001
  644 1033
  560 11728
  475 11707
  470 1904
  420 1
  409 8194
  387 1003
...

PS C:\> $e= ($d | group -property Message -noelement | sort -desc -property Count)
PS C:\> $e.count
9644

PS C:\> $e.Values[0,1,2]
The description for Event ID '0' in Source 'gupdate' cannot be found.  The local computer may not have the necessary registry information or message DLL files to displ
ay the message, or you may not have permission to access them.  The following information is part of the event:'Service stopped'
The description for Event ID '0' in Source 'gupdate' cannot be found.  The local computer may not have the necessary registry information or message DLL files to displ
ay the message, or you may not have permission to access them.  The following information is part of the event:'Service started'
Failed extract of third-party root list from auto update cab at: with e
rror: A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file.
...

2 comments:

  1. its nice post about the security thanks for providing such useful information actually there should be proper councling about the Security Course it provides a better security tricks along with to brighten someone's career.....

    ReplyDelete
  2. nice blog, very good information! btw, I also have a blog and a web directory, would you like to exchange links? let me know on emily.kovacs14@gmail.com

    ReplyDelete