Windows Event Log, sistem yöneticilerinin sorun analiz etmek, sorunun kaynağına inmek yada günlük rutin işlemleri takip ettiğimiz  günlüğümüzü biraz da PowerShell tarafından inceleyerek sizlere anlatmak isterim. 

İlk olarak PowerShell üzerinde Event logları nasıl görüntüleyebiliriz inceleyelim. "Get-EventLog" komutu ile özelikle uzak bir lokasyonda bulunan sunucumuza erişim sağlayarak hızlı ve pratik bir şekilde logları inceleyebiliriz. PowerShell hayatımıza girdiğinden beri sistem yöneticileri bir kaç komut ile sabah kahvesi yudumlarken işlmelerini sürdürüyor ve logları hızlı bir şekilde inceleyebiliyor. 

Get-EventLog komutunu ilk kez kullanacaksanız mutlaka -? parametresi ile ilgili help modülünü yükleyiniz. 

Get-EventLog -?

Komutumuzu çalıştırarak "Y" olarak onay verip ilgili help modülünü yüklüyoruz. 

PS C:\Users\Administrator> Get-EventLog -?
 
Do you want to run Update-Help?
The Update-Help cmdlet downloads the most current Help files for Windows PowerShell modules, and installs them on your computer. For more information about the Update-Help cmdlet, see
https:/go.microsoft.com/fwlink/?LinkId=210614.
[Y] Yes  [N] No  [S] Suspend  [?] Help (default is "Y"): y

Get-EventLog yardım içeriği aşağıdaki gibidir. 

PS C:\Users\Administrator> Get-EventLog -?
 
NAME
    Get-EventLog
 
SYNOPSIS
    Gets the events in an event log, or a list of the event logs, on the local or remote computers.
 
 
SYNTAX
    Get-EventLog [-LogName] <String> [[-InstanceId] <Int64[]>] [-After <DateTime>] [-AsBaseObject] [-Before <DateTime>] [-ComputerName <String[]>] [-EntryType {Error | Information | FailureAudit | SuccessAudit | Warning}
    ] [-Index <Int32[]>] [-Message <String>] [-Newest <Int32>] [-Source <String[]>] [-UserName <String[]>] [<CommonParameters>]
 
    Get-EventLog [-AsString] [-ComputerName <String[]>] [-List] [<CommonParameters>]
 
 
DESCRIPTION
    The Get-EventLog cmdlet gets events and event logs on the local and remote computers.
 
    You can use the parameters of this cmdlet to search for events by using their property values. This cmdlet gets only the events that match all of the specified property values.
 
    The cmdlets that contain the EventLog noun work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent.
 
 
RELATED LINKS
    Clear-EventLog
    Limit-EventLog
    New-EventLog
    Remove-EventLog
    Show-EventLog
    Write-EventLog
 
REMARKS
    To see the examples, type: "get-help Get-EventLog -examples".
    For more information, type: "get-help Get-EventLog -detailed".
    For technical information, type: "get-help Get-EventLog -full".
    For online help, type: "get-help Get-EventLog -online"

Sık kullanacağınız bazı komutları sizin ile paylaşmak isterim örneğin event log içeriklerini listelemek için "Get-EventLog -list" komutunu kullanabilirsiniz.

Get-EventLog -list

PS C:\Users\Administrator> Get-EventLog -list
 
  Max(K) Retain OverflowAction        Entries Log
  ------ ------ --------------        ------- ---
  20.480      0 OverwriteAsNeeded       2.639 Application
  20.480      0 OverwriteAsNeeded           0 HardwareEvents
     512      7 OverwriteOlder              0 Internet Explorer
  20.480      0 OverwriteAsNeeded          26 Key Management Service
     512      7 OverwriteOlder          1.233 Microsoft-ServerManagementExperience
     512      7 OverwriteOlder                Parameters
  20.480      0 OverwriteAsNeeded      33.374 Security
     512      7 OverwriteOlder                State
  20.480      0 OverwriteAsNeeded      69.574 System
  15.360      0 OverwriteAsNeeded      10.909 Windows PowerShell

Şimdiki örneğimizde "Get-Eventlog -application" komutu ile uygulamalarımızda ki logları görüntüleyelim. 

Get-EventLog Application

Çıktısı çok uzun olduğu için sadece bir bölümünü koyuyorum 

Index Time          EntryType   Source                 InstanceID Message
----- ----          ---------   ------                 ---------- -------
 2639 May 31 09:16  Information Desktop Window Ma...   1073750851 The Desktop Window Manager has registered the session port.
 2638 May 31 08:11  Information ESENT                         326 svchost (1060,D,50) DS_Token_DB: The database engine attached a database (1, C:\Windows\system32\config\systemprofile\AppData\Local\DataSharing\Stor...
 2637 May 31 08:11  Information ESENT                         105 svchost (1060,D,0) DS_Token_DB: The database engine started a new instance (0). (Time=0 seconds)...
 2636 May 31 08:11  Information ESENT                         302 svchost (1060,U,98) DS_Token_DB: The database engine has successfully completed recovery steps.
 2635 May 31 08:11  Information ESENT                         301 svchost (1060,R,98) DS_Token_DB: The database engine has finished replaying logfile C:\Windows\system32\config\systemprofile\AppData\Local\DataShari...
 2634 May 31 08:11  Information ESENT                         300 svchost (1060,R,98) DS_Token_DB: The database engine is initiating recovery steps.
 2633 May 31 08:11  Information ESENT                         102 svchost (1060,P,98) DS_Token_DB: The database engine (10.00.17763.0000) is starting a new instance (0).
 2632 May 31 06:59  Information gupdate                         0 The description for Event ID '0' in Source 'gupdate' cannot be found.  The local computer may not have the necessary registry information or message...
 2631 May 31 06:54  Information Software Protecti...   1073742827 The Software Protection service has completed licensing status check....
 2630 May 31 01:59  Information gupdate                         0 The description for Event ID '0' in Source 'gupdate' cannot be found.  The local computer may not have the necessary registry information or message...
 2629 May 30 20:59  Information gupdate                         0 The description for Event ID '0' in Source 'gupdate' cannot be found.  The local computer may not have the necessary registry information or message...

Tabi bu şekilde bir sorun analiz etmek çok zor olabilir. Biraz daha net bilgi edinmek için komutumu biraz daha geliştiriyorum. "Get-EventLog Application -EntryType Error" komutu ile sadece error veren applicationların loglarını çıktısını alıyorum. 

Get-EventLog Application -EntryType Error

PS C:\Users\Administrator> Get-EventLog Application -EntryType Error
 
   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
    2616 May 30 18:14  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2607 May 30 18:12  Error       PerfNet                3221227476 The description for Event ID '-1073739820' in Source 'PerfNet' cannot be found.  The local computer may not have the necessary registry information ...
    2539 May 30 18:11  Error       Microsoft-Windows...         1000 Access to performance data was denied to user "Administrator" (value from GetUserName() for the running thread) as attempted from module "C:\Windows...
    2526 May 30 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2521 May 29 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2513 May 28 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2507 May 27 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2502 May 26 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2496 May 25 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2470 May 24 09:44  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2461 May 24 09:42  Error       PerfNet                3221227476 The description for Event ID '-1073739820' in Source 'PerfNet' cannot be found.  The local computer may not have the necessary registry information ...
    2380 May 23 17:01  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....
    2374 May 22 17:01  Error       Software Protecti...   1073754117 Publishing the Key Management Service (KMS) to DNS in the '' domain failed....

İşi biraz daha filtreli bir hale getirelim bu seferde yeni olan logları çekelim. Sonuçları filtrelemek için Get-Member yönlendiriyorum. 

Get-EventLog application -newest 1 | Get-Member

PS C:\Users\Administrator> Get-EventLog application -newest 1 | Get-Member
 
 
   TypeName: System.Diagnostics.EventLogEntry#application/Desktop Window Manager/1073750851
 
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.StreamingContext context)
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;}

Farklı bir şey deneyelim örneğin event ID 7001 olan logları sıralatalım. Bugün oluşan ve ID si 7001 olan sonuçları listeleyelim. 

Get-EventLog system -after (get-date).AddDays(-1) | where {$_.InstanceId -eq 7001}

PS C:\Users\Administrator> Get-EventLog system -after (get-date).AddDays(-1) | where {$_.InstanceId -eq 7001}
 
   Index Time          EntryType   Source                 InstanceID Message
   ----- ----          ---------   ------                 ---------- -------
   78659 May 31 09:16  Information Microsoft-Windows...         7001 User Logon Notification for Customer Experience Improvement Program

Benim en sevdiğim komutlardan biri olan sunucu üzerine kim logon oldu kim logoff oldu loglardan toplayan aşağıdaki komutu kullanabilirsiniz. 

$logs = get-eventlog system -ComputerName powershell-ozan -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7);
$res = @(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property @{Time = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}};
$res

Uygulaması aşağıdaki gibidir. 

PS C:\Users\Administrator> $logs = get-eventlog system -ComputerName powershell-ozan -source Microsoft-Windows-Winlogon -After (Get-Date).AddDays(-7);
PS C:\Users\Administrator> $res = @(); ForEach ($log in $logs) {if($log.instanceid -eq 7001) {$type = "Logon"} Elseif ($log.instanceid -eq 7002){$type="Logoff"} Else {Continue} $res += New-Object PSObject -Property @{Time
 = $log.TimeWritten; "Event" = $type; User = (New-Object System.Security.Principal.SecurityIdentifier $Log.ReplacementStrings[1]).Translate([System.Security.Principal.NTAccount])}};
PS C:\Users\Administrator> $res
 
Time                User                          Event
----                ----                          -----
31.05.2019 09:16:58 POWERSHELL-OZAN\Administrator Logon
30.05.2019 18:11:02 POWERSHELL-OZAN\Administrator Logoff

Temel olarak event log kullanımını PowerShell ile bu şekilde yapabilir örnek scrtiptleri kendinize göre düzenleyip kullanabilirsiniz. 

Kaynak: https://www.codetwo.com
Kaynak: https://microsoft.com