Журнал событий Windows (Event Log) — это важный инструмент, который позволяет администратору отслеживать ошибки, предупреждения и другие информационные сообщения, которые регистрируются операционной системой, ее компонентами и различными программами. Для просмотра журнала событий Windows можно использовать графическую MMC оснастку Event Viewer (
eventvwr.msc
). В некоторых случаях для поиска информации в журналах событий и их анализа гораздо удобнее использовать PowerShell. В этой статье мы покажем, как получать информацию из журналов событий Windows с помощью командлета Get-WinEvent.
Содержание:
- Получение логов Windows с помощью Get-WinEvent
- Get-WinEvent: быстрый поиск в событиях Event Viewer с помощью FilterHashtable
- Расширенный фильтры событий Get-WinEvent с помощью FilterXml
- Получить логи Event Viewer с удаленных компьютеров
На данный момент в Windows доступны два командлета для доступа к событиям в Event Log: Get-EventLog и Get-WinEvent. В подавляющем большинстве случаев рекомендуем использовать именно Get-WinEvent, т.к. он более производителен, особенно в сценариях обработки большого количества событий с удаленных компьютеров. Командлет Get-EventLog является устаревшим и использовался для получения логов в более ранних версиях Windows. Кроме того, Get-EventLog не поддерживается в современных версиях PowerShell Core 7.x.
Получение логов Windows с помощью Get-WinEvent
Для использования команды Get-WinEvent нужно запустить PowerShell с правами администратора (при запуске Get-WinEvent от имени пользователя вы не сможете получить доступ к некоторым логам, например, к Security).
Для получения списка событий из определенного журнала, нужно указать его имя. В данном примере мы выведем последние 20 событий из журнала System:
Get-WinEvent -LogName Application -MaxEvents 20
Чаще всего вам нужно будет получать информацию из журналов System, Application, Security или Setup. Но вы можете указать и другие журналы. Полный список журналов событий в Windows можно получить с помощью команды:
Get-WinEvent -ListLog *
Например, чтобы вывести события RDP подключений к компьютеру, нужно указать лог Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational:
Get-WinEvent -LogName Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational
Или получить логи SSH подключений к Windows из журнала OpenSSH/Operational:
Get-WinEvent -LogName OpenSSH/Operational
Можно выбрать события сразу из нескольких журналов. Например, чтобы получить информацию о ошибках и предупреждениях из журналов System и Application за последние 24 часа (сутки), можно использовать такой код:
$StartDate = (Get-Date) - (New-TimeSpan -Day 1)
Get-WinEvent Application,System | Where-Object {($_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning") -and ($_.TimeCreated -ge $StartDate )}
Чтобы вывести только определенные поля событий, можно использовать Select-Object или Format-Table:
Get-WinEvent -LogName System | Format-Table Machinename, TimeCreated, Id, UserID
Можно выполнить дополнительные преобразования с полученными данными. Например, в этом примере мы сразу преобразуем имя пользователя в SID:
Get-WinEvent -filterhash @{Logname = 'system'} |
Select-Object @{Name="Computername";Expression = {$_.machinename}},@{Name="UserName";Expression = {$_.UserId.translate([System.Security.Principal.NTAccount]).value}}, TimeCreated
Get-WinEvent: быстрый поиск в событиях Event Viewer с помощью FilterHashtable
Рассмотренный выше способ выбора определенных событий из журналов Event Viewer с помощью Select-Object прост для понимая, но выполняется крайне медленно. Это особенно заметно при выборке большого количества событий. В большинстве случаев для выборки событий нужно использовать фильтрацию на стороне службы Event Viewer с помощью параметра FilterHashtable.
Попробуем сформировать список ошибок и предупреждений за 30 дней с помощью Where-Object и FilterHashtable. Сравнима скорость выполнения этих двух команд PowerShell с помощью Measure-Command:
$StartDate = (Get-Date).AddDays(-30)
Проверим скорость выполнения команды с Where-Object:
(Measure-Command {Get-WinEvent Application,System | Where-Object {($_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning") -and ($_.TimeCreated -ge $StartDate )}}).TotalMilliseconds
Аналогичная команда с FilterHashtable:
(Measure-Command {Get-WinEvent -FilterHashtable @{LogName = 'System','Application'; Level =2,3; StartTime=$StartDate }})..TotalMilliseconds
В данном примере видно, что команда выборки событий через FilterHashtable выполняется в 30 раз быстрее, чем если бы обычный Where-Object (
2.5
сек vs
76
секунд).
Если вам нужно найти события по EventID, используйте следующую команду с FilterHashtable:
Get-WinEvent -FilterHashtable @{logname='System';id=1074}|ft TimeCreated,Id,Message
В параметре FilterHashtable можно использовать фильтры по следующим атрибутам событий:
- LogName
- ProviderName
- Path
- Keywords (для поиска успешных событий нужно использовать значение 9007199254740992 или для неуспешных попыток 4503599627370496)
- ID
- Level (1=FATAL, 2=ERROR, 3=Warning, 4=Information, 5=DEBUG, 6=TRACE, 0=Info)
- StartTime
- EndTime
- UserID (SID пользователя)
- Data
Пример поиска события за определенный промежуток времени:
Get-WinEvent -FilterHashTable @{LogName='System'; StartTime=(get-date).AddDays(-7); EndTime=(get-date).AddHours(-1); ID=1234}
Если нужно найти определенный текст в описании события, можно использовать такую команду:
Get-WinEvent -FilterHashtable @{logname='System'}|Where {$_.Message -like "*USB*"}
Расширенный фильтры событий Get-WinEvent с помощью FilterXml
Фильтры Get-WinEvent с параметром FilterHashtable являются несколько ограниченными. Если вам нужно использовать для выборки событий сложные запросы с множеством условий, нужно использовать параметр FilterXml, который позволяет сформировать запрос на выбор событий в Event Viewer с помощью XML запроса. Как и FilterHashtable, фильтры FilterXml выполняется на стороне сервера, поэтому результат вы получите довольно быстро.
Например, аналогичный запрос для получения последних ошибок из журнала System за последние 30 дней может выглядеть так:
$xmlQuery = @'
<QueryList>
<Query Id="0" Path="System">
<Select Path="System">*[System[(Level=2 or Level=3) and TimeCreated[timediff(@SystemTime) <= 2592000000]]]</Select>
</Query>
</QueryList>
'@
Get-WinEvent -FilterXML $xmlQuery
Для построения кода сложных XML запросов можно использовать графическую консоль Event Viewer:
- Запустите
eventvwr.msc
; - Найдите журнал для которого вы хотите создать и выберите Filter Current Log;
- Выберите необходимые параметры запроса в форме. В этом примере я хочу найти события с определенными EventID за последние 7 дней от определенного пользователя;
- Чтобы получить код XML запроса для параметра FilterXML, перейдите на вкладку XML и скопируйте полученный код (CTRL+A, CTRL+C);
- Если нужно, вы можете вручную отредактировать данный запрос.
Для экспорта списка событий в CSV файл нужно использовать командлет Export-CSV:
$Events= Get-WinEvent -FilterXML $xmlQuery
$events| Export-CSV "C:\ps\FilterSYSEvents.csv" -NoTypeInformation -Encoding UTF8
Получить логи Event Viewer с удаленных компьютеров
Для получения события с удаленного компьютер достаточно указать его имя в параметре -ComputerName:
$computer='msk-dc01'
Get-WinEvent -ComputerName $computer -FilterHashtable @{LogName="System"; StartTime=(get-date).AddHours(-24)} | select Message,Id,TimeCreated
Можно опросить сразу несколько серверов/компьютеров и поискать на них определенные события. Список серверов можно получить из текстового файла:
$servers = Get-Content -Path C:\ps\servers.txt
Или из Active Directory:
$servers = (Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"').Name
foreach ($server in $servers) {
Get-WinEvent -ComputerName $server -MaxEvents 5 -FilterHashtable @{
LogName = 'System'; ID= 1234
} | Select-Object -Property ID, MachineName
}
Здесь есть другой пример для поиска событий блокировки учетной записи пользователя на всех контроллерах домена:
$Username = 'a.ivanov'
Get-ADDomainController -fi * | select -exp hostname | % {
$GweParams = @{
‘Computername’ = $_
‘LogName’ = ‘Security’
‘FilterXPath’ = "*[System[EventID=4740] and EventData[Data[@Name='TargetUserName']='$Username']]"
}
$Events = Get-WinEvent @GweParams
$Events | foreach {$_.Computer + " " +$_.Properties[1].value + ' ' + $_.TimeCreated}
}
Being able to track what PowerShell scripts are doing is important, especially in a production environment. Recording activity is key to troubleshooting, auditing, and investigating potential security issues. Using PowerShell and a community module known as PSFramework allows you to take your logging to a whole new level which you’ll learn about in this article!
If you find yourself using the Write-Host
cmdlet to display error information or manually registering Windows event sources, this article is for you.
Stay with us if you want a simple, scalable PowerShell logging solution that can write to a text file or integrate into a log management solution.
Creating Better Log Messages
Before deciding on how best to generate logs with PowerShell, you need to first understand how to come up with better log messages, to begin with.
There are many reasons to generate logs. One of the most common is the infamous error message. Error messages can be helpful or harmful depending on how you look at things.
You’ve undoubtedly been victim to some bad error messages in your day. If you’ve ever seen the movie Office Space, PC LOAD LETTER is a prime example.
If your error messages cause someone to think, “WTF does that mean?”, you should consider rewriting your message! Logs should be clear and concise.
Make Events Actionable
A log message indicating a cryptic PC LOAD LETTER error message by itself doesn’t make a lot of sense. No one is going to know what that message means including you a few years from now! You should always generate log messages for error conditions that are actionable.
Using the PC LOAD LETTER message for example, what would you think if it instead said, “PC LOAD LETTER: Check the specs on the rotary girder. If within spec, contact vendor support for further guidance“? You’d probably keep your cool a bit more and actually have a jumpstart on fixing the problem.
Keep Logs Simple and Human-Readable
Log information must be human-readable. Include enough information to make the event actionable and not left to guesswork. You can be precise, but make sure you can have someone else understand, even if on a basic level, what the event means.
Logging is only as complicated as you want to make it. Keeping logs simple makes troubleshooting easier for all involved.
Logging Options in Windows
When you hear the word ‘log’ in IT, what comes to mind? Chances are you immediately begin to think about log files. Although log files are, indeed, an option and one you’ll learn about in this article, they aren’t the only option.
Another alternative is the Windows Event Log. The Windows Event Log and it’s seemingly endless number of log sources is ubiquitous in Windows. The event log allows you to write logs the varying degrees of severity, sources, categories, messages, and more.
The Windows Event Log differs from a log file because it has structure. A log file, on its own, is a simple text file. It’s up to the developer to come up with a schema for the log messages. The Windows Event log already has the schema taken care of.
Throughout this article, we’ll cover using PowerShell to work with the event log. We’ll also cover logging with log files using the PSFramework PowerShell module.
Prerequisites
The remainder of this article is going to be a walkthrough. If you’ll be following along, you’ll need to ensure we’re both on the same page. To work through each topic in this article, you’ll need:
- Windows PowerShell 5.1
- intermediate knowledge of PowerShell
- to understand basic Windows event logging terminology
Writing Events to the Windows Event Log
One way to capture logging information with PowerShell is to use the Windows Event Log. As mentioned earlier, the Windows Event Log already provides a schema to work with. It also includes GUI tools like the Windows Event Viewer and PowerShell cmdlets to create and parse event log messages.
The main PowerShell cmdlet you’ll use to write log events to the Windows Event Log is the Write-EventLog
cmdlet. The Write-EventLog
cmdlet is how you can generate new log events in existing event logs. If you’re planning on using existing event sources like the Application, Security, System event logs, the Write-EventLog
cmdlet is all you need.
The Windows Event Log has a concept known as sources. In a nutshell, a source is simply a way to put event log messages into buckets. Built-in sources are used to separate operating system-specific events from software events, for example.
Using existing sources to write events works just fine if you’d like your log message to show up in a default source. But you can also create your own sources which will help differentiate your custom-generated event log messages from all the others.
Creating an Event Log Source
You can create a custom event log source by using the New-EventLog
cmdlet. This cmdlet will modify the registry to make your event log a first-class citizen in Windows.
From an administrative PowerShell console, register a new event log source providing a name and source as shown below.
PS51> New-EventLog -LogName 'Application' -Source 'ATA_Script’'
If you don’t have appropriate permissions or are running the command under a non-elevated PowerShell console session, you will see an error like below.
Creating Event Log Entries
Once you’ve created a source for your script/application, you can then get down to business and begin generating event log messages using the Write-EventLog
cmdlet.
Below you can see an example of writing an event log message to the Application event log using the event source just created (ATA_Script). This message is an Informational event with an ID of 1.
PS51> Write-EventLog -LogName 'Application' -Source 'ATA_Script' -EntryType 'Information' -EventID 1 -Message 'Everything is broken. Everything is cool when you’re part of a team!'
Once the event is created, you can then find this event in the Windows Event Viewer or using PowerShell using the Get-WinEvent
or the Get-EventLog
cmdlet. The below example is using the Get-EventLog
cmdlet to find all Informational events using the event source just created. If more than one event is returned, it returns the newest one.
PS51> Get-EventLog -LogName 'Application' -EntryType 'Information' -Source 'ATA_Script’' -Newest 1
Event Source Best Practice
Before you leave this section, it’s important you know about a gotcha here. In the above example, PowerShell is using the arbitrary registered source (ATA_Script) created earlier. This source is required to write an entry to the Windows Application log.
Using a custom sources like this works well for simple scenarios like:
- Event logging for a custom Windows service.
- Recording results from a simple PowerShell function.
- Providing a trigger event for another process.
As a best practice, register a new event source for each script you want to generate event log entries as shown in the first step. When you do it this way, it’s easier to keep track of what is generating the event log entries. Imagine you have five scripts, each doing a very specific task. If all of them were using the same event source, how could you determine which script had failure? Registering a new event source helps you organize your logging sources.
Leveraging PowerShell Transcripts
Although the method you’re about to learn works, it’s not the best way. You’ll see why in a bit.
Although the Write-Host
cmdlet is useful when you need some visual feedback when a script runs, it’s not great at logging. Why?
- The output is specific to a single PowerShell session. When you close the session, the output is gone.
- The cmdlet doesn’t have much customization beyond foreground and background colors of text.
Below you can see an example of what Write-Host
cmdlet looks like in use.
Although by default, this output is only displayed to the PowerShell console and not recorded anywhere else, it can be using PowerShell transcripts.
Using the Start-Transcript
cmdlet, you can create transcripts (text files) that capture all output sent to a PowerShell console. The Start-Transcript
cmdlet is a great way to record PowerShell session activity.
While the Start-Transcript
cmdlet starts recording console activity to a new transcript, the Stop-Transcript
cmdlets stops it. You can see an example below.
Although using the Write-Host
cmdlet and PowerShell transcripts technically works, it’s not the greatest solution. Notice what the transcript contains in the example below. The log is difficult to read and is near impossible to parse!
Logging with the PSFramework PowerShell Module
As promised, it’s time to get into logging to text files! Although, you could roll your own log file solution using a combination of the Add-Content
, Set-Content
and other PowerShell cmdlets, there’s no need. You can use a free PowerShell module called PSFramework!
PSFramework is a PowerShell module that allows you to log activity in a variety of different scenarios.
Important PSFramework Concepts
Providers
A key concept of the PSFramework module is providers. Providers are pointers to various destinations you’d like logs to be stored in. A provider could be something like Kiwi Log Server, Elasticsearch, loggly, Graylog or something as basic as a file (usually text).
Although extensible, when you first download the PSFramework module, you immediately get three providers to use:
- Filesystem – This provider writes all message streams you create to the currently-logged-in user’s %APPDATA% folder with automatic seven-day retention and rotation. Filesystem is the default provider.
- Gelf – This provider allows PSFramework to send log message streams to an open source log manager called Graylog. There is a little more setup involved when using this option.
- Logfile – This provider allows you to specify a file to write all messages to. Because a log file could be of various types, the default output is CSV-formatted. This means you can use common log file extensions like .txt, .log, or .csv. The choice is yours.
Message Streams
Message streams contain output from commands. These are used to classify information being recorded in the logs. Common streams are Verbose, Debug, Information, Error and Warning. You can read more about available streams using Help about_psf_message
.
Let’s get down to actually use the PSFramework module now and see what it can do!
Install PSFramework
The first task is to download and install this module. To do so, download it from the PowerShell Gallery by running Install-Module -Name PSFramework -Scope CurrentUser
. This will place the module in my user profile rather than the system path. If you’d like to make the module available to all users on your system, don’t use the Scope
parameter.
Once installed, you will now have access to all the cmdlets that are required for the code examples demonstrated in the rest of this article.
Setting up a Provider
There are three registered and installed providers available to choose from with the default PSFramework configuration – filesystem, logfile, and greylog. If you want to use another provider, you will first register and then install that provider within PSFramework. Before you can start writing to logs, you must enable one of these providers.
The command to enable a provider is Set-PSFLoggingProvider
. This cmdlet has two required parameters – Name
andEnable
. You’ll use each parameter to enable the provider or providers you wish to work with.
If you plan on using your own provider, you will need to run the Register-PSFLoggingProvider
and the Install-PSFLoggingProvider
cmdlets. These cmdlets and scenario are outside the intended scope of this article. If you wish to explore this option further, consult the built-in help provided with the module. There are some examples that could lead you to expanding on existing capabilities and provide you with a deeper understanding of how logging works.
For this demonstration, you’ll be using the logfile provider. Since this provider is off by default, you must first enable the provider so that message streams can be sent to it. Using the Set-PSFLoggingProvider
command, you can do that no sweat:
Set-PSFLoggingProvider -Name 'logfile' -Enable $true
If you want to stick with the filesystem provider, no action would be required on your part as it’s already enabled by default.
To see all of the currently-registered providers, run the Get-PSFLoggingProvider
command. This command should return output similar to the screenshot below.
Now that you’ve enabled a provider, you can begin sending message streams to that provider you wish to use for your logging solution.
Logging with the filesystem Provider
The filesystem provider provides a quick way to start logging without having to configure storage locations for log files. It’s perfect for short-term logging needs, but not one where you need long-term diagnostic logging.
In this demonstration of the filesystem provider, you’re going to learn how to use the Write-PSFMessage
cmdlet. Imagine you’ve got an existing PowerShell script that starts a service on a remote host. Sometimes the service doesn’t start for some reason and the errors generated are not being captured. You can see the example below.
Invoke-Command -ComputerName 'Lab01.domain.local' -ScriptBlock { Start-Service -Name 'BITS' }
You’d like to know the Start-Service
command is able to successfully start the service and when it fails. To do so, you force Start-Service
to return a terminating error and then add try/catch blocks to catch any errors that happen.
try {
Invoke-Command -ComputerName 'Lab01.domain.local' -ScriptBlock { Start-Service -Name 'BITS' } -ErrorAction Stop
} catch {
}
You now need to log both when Start-Service
is successful and when it fails. You know that if Invoke-Command
fails, PowerShell will run code inside of the catch
block and not any code after Invoke-Command
runs.
Contrast that behavior with a success where code after Invoke-Command
will run. You decide to run theWrite-PSFMessage
command in the appropriate spots.
As you can see below, if the code successfully executes, Write-PSFMessage
will record a helpful message with a level of Important
and tagged as Success
.
try {
Invoke-Command -ComputerName 'Lab01.domain.local' -ScriptBlock { Start-Service -Name 'BITS' } -ErrorAction Stop
Write-PSFMessage -Level Important -Message 'Successfully started BITS.' -Tag 'Success'
} catch {
Write-PSFMessage -Level Warning -Message 'Error starting BITS.' -Tag 'Failure' -ErrorRecord $_
}
Above you saw a use of the
Tags
feature. Tags are optional, but it does make it easier when needing to sort and search a log. Tags are free text allowing you to define your own. Some common tags are SUCCESS, FAILURE, ERROR and INFO.
Now if the command fails, you will see a warning written to the PowerShell console as shown below.
Viewing the filesystem Log
Once you’ve written a few message streams with the filesystem provider, you can use the Get-PSFMessage
cmdlet to query the log.
If the code in the example above generated log messages at the Warning level, you could read all of those messages by using a value of Warning
for the Level
parameter. You can see an example of how to do this along with the output type you will receive.
PS51> Get-PSFMessage -Level Warning
Logging with the logfile Provider
Now that you’ve seen how the filesystem provider works, let’s check out the logfile provider. The logfile providers allows you to write message streams to plain-text files, by default, in a CSV format.
To use the logfile provider, you’ll first have to tell PSFramework to not use the default provider (filesystem) and to set a file to record messages to. To do so, use the Set-PSFLoggingProvider
cmdlet. You can see in the below example how to do this.
- name of the provider (logfile) via the
Name
parameter - setting the
Enabled
property to True - setting the destination file as the value for
FilePath
PS51> Set-PSFLoggingProvider -Name logfile -Enabled $true -FilePath 'C:\My_Events.log'
Note: Be sure to set the provider at the beginning of your script!
When a message is received via running the Write-PSFMessage
command as before, PSFramework will record the message. The message will include a date format of mm:dd:yyyy, script name (source), message level, a verbose message, tag (optional), and an error record.
Below is an example of what a single log message will look like in Windows notepad in an unstructured format.
To take advantage of the CSV format, open the log file up in Microsoft Excel and the output will look much better as shown below.
My choice to use the logfile provider instead of the filesystem provider was due to a need to keep a long running history and import information into Excel. The format of the output makes it a breeze to generate charts and filter data for reporting.
Bonus: Querying Logs by Runspace
An advanced feature of the PSFramework module is working with runspaces. A PowerShell runspace is a commonway you can run processes in parallel by spinning up threads.
Since you may have multiple streams of logging running at once in different runspaces, PSFramework allows you to look at multiple logs in real time. These logs can come from many sources through the use of runspaces. This feature is extremely useful as you can leave a single PowerShell session open while running multiple commands or scripts in the background.
If you know the runspace ID, you can specify it using the Runspace
parameter on the Get-PSFMessage
command as shown below.
Get-PSFMessage -Runspace a2346978-d324-4886-89b8-bd14769be78f
Runspace can be a complicated topic to grasp. If you would like to learn more, check out this Microsoft DevBlog Series about using runspaces.
I’ve been using the PSFramework module for months now and it has supercharged my maintenance scripts and forced me to write better code.
It’s forced me to write better error handling code and to make a habit of setting the common ErrorAction
parameter to True on cmdlets to create terminating errors.
I started seeing the benefits instantly. There’s even been an ongoing problem I was able to finally solve using the log file that was generated.
I was running into an error that only occurred when executing a script using scheduled jobs. The script would run fine when executed manually. The issue turned out to be a credential and timing issue. Since the error record ID was in the log file, error messages were clear and using tags, I was able to narrow it down in no time.
Having tried other methods to generate log files and this module is by far the easiest to use.
The PSFramework is module works great, is reliable, and gives you the most control over verbose messages.
Summary
As you’ve learned throughout this article, logging should be a key component of your automation processes. Establishing clear logging guidelines with informative and actionable logs coupled with understanding logging options will go a long way.
If you haven’t used the PSFramework module and haven’t walked through the demos provided here, please do so. This helpful module allows you to many different options in recording logs which will ultimately help troubleshooting, auditing and security analysis.
Further Reading
- PSFramework Documentation
- Friedrich Weinmann: Logging in a DevOps World
- How to Use PowerShell Transcripts by Adam Bertram
The `Get-WinEvent` cmdlet in PowerShell retrieves events from the Windows Event Log or from event log files, allowing users to filter and analyze system, application, and security events efficiently.
Here’s a code snippet to illustrate its usage:
Get-WinEvent -LogName Application -MaxEvents 10
PowerShell Get-WinEvent is a powerful cmdlet used for managing and gathering information from the Windows Event Logs. Designed as a more modern alternative to the older `Get-EventLog` cmdlet, `Get-WinEvent` allows system administrators and advanced users to access a wider variety of logs, including both the traditional Windows logs and custom logs created by applications.
Mastering PowerShell Get-Credential: A Quick Guide
Why Use Get-WinEvent?
Utilizing Get-WinEvent provides numerous advantages:
- Performance Enhancements: It is optimized to handle larger amounts of data and process logs more quickly than its predecessors.
- Flexibility: It allows you to filter, sort, and manipulate event data, making it easier to find what you need.
- Rich Data: The cmdlet retrieves extensive details about events, enabling in-depth system analysis.
Understanding PowerShell Requirements for Efficient Use
Understanding Event Logs in Windows
Types of Windows Event Logs
Windows Event Logs can be broadly categorized as follows:
- Application Logs: Contains entries related to applications and their performance.
- System Logs: Captures system-level events, such as driver or hardware issues.
- Security Logs: Focuses on security-related events, like login attempts and access to files.
- Custom Logs: Allows applications to generate their own logs for specific needs.
Structure of Event Logs
Each event log entry has a consistent structure that generally includes the following:
- Timestamp: The date and time the event occurred.
- Event ID: A unique identifier for the event type.
- Level: Severity of the event, categorized as Warning, Error, or Information.
- Source and Message: Specific information about what triggered the event and a description.
Mastering PowerShell Get Input: A Quick Guide
Getting Started with Get-WinEvent
Basic Syntax of Get-WinEvent
The basic syntax of the `Get-WinEvent` command is as follows:
Get-WinEvent -LogName <LogName>
Running Your First Get-WinEvent Command
To retrieve entries from the Application log, you would execute:
Get-WinEvent -LogName Application
This command will fetch all records in the Application log, allowing you to start exploring what each entry contains.
PowerShell Get Timestamp: Quick and Easy Guide
Filtering Events with Get-WinEvent
Using Filters for Specific Logs
One of the strengths of Get-WinEvent is the ability to filter logs effectively. For instance, if you want to find only the error events within the System log, you could write:
Get-WinEvent -LogName System | Where-Object { $_.Level -eq 'Error' }
This command retrieves only those events classified as Errors, helping you quickly identify critical issues.
Using Event IDs for Specific Issues
Events can also be filtered by their Event ID. For example, to check for logon events, you might use:
Get-WinEvent -LogName Security -Id 4624
Event ID 4624 indicates a successful logon. Tracking logon events is essential for security audits.
PowerShell Get File Extension: A Quick Guide
Customizing Output
Selecting Properties to Display
Sometimes, logs contain a wealth of information. To display only specific properties, you can customize your output like this:
Get-WinEvent -LogName Application | Select-Object TimeCreated, ProviderName, Message
This command will show only the creation time, provider name, and the message associated with each event, making it easier to review.
Exporting Event Logs to CSV
You may need to analyze logs further, and saving them for later use can be beneficial. You can export log entries into a CSV file with:
Get-WinEvent -LogName System | Export-Csv -Path "SystemEvents.csv" -NoTypeInformation
This command creates a CSV file containing all System log entries, facilitating easier manipulation and review in spreadsheet applications.
Mastering PowerShell Get-CimInstance Made Simple
Advanced Usage of Get-WinEvent
Combining Get-WinEvent with Other Cmdlets
To enhance data manipulation, `Get-WinEvent` can be combined with other cmdlets like `Sort-Object`. For example, to retrieve Application logs sorted by their timestamp in descending order:
Get-WinEvent -LogName Application | Sort-Object TimeCreated -Descending
This command presents the most recent events first, which is particularly useful in troubleshooting scenarios.
Using Get-WinEvent with Filters and Time Windows
You can further narrow down your searches by specifying a time frame. For example, to find System events from the last week, you would use:
Get-WinEvent -LogName System -StartTime (Get-Date).AddDays(-7) -EndTime (Get-Date)
This command efficiently filters events that occurred in the last seven days, making your log reviews more focused.
Mastering PowerShell Get-ADObject: A Quick Guide
Practical Scenarios for Get-WinEvent
Monitoring System Health
Using `Get-WinEvent` can be invaluable in monitoring system health. By regularly checking logs for specific warnings or errors, you can proactively address potential issues before they escalate into critical failures.
Security Auditing with Event Logs
In the realm of security, `Get-WinEvent` is a critical tool. It allows you to track user activities, such as logins and file access, enabling you to identify unauthorized access attempts or other suspicious behavior.
Set Timezone in PowerShell: A Quick How-To Guide
Conclusion
To conclude, PowerShell Get-WinEvent is an essential cmdlet for effective event log management on Windows systems. Its flexibility, power, and ease of use make it an invaluable tool for system administrators. By mastering `Get-WinEvent`, you enhance your ability to troubleshoot issues, monitor system health, and perform security audits efficiently.
PowerShell Get Time: Quick Command for Current Time Insights
FAQs about PowerShell Get-WinEvent
-
What types of logs can be retrieved?
You can retrieve logs from the Application, System, Security, and custom logs created by applications. -
How can Get-WinEvent improve troubleshooting processes?
By quickly accessing detailed event logs, you can identify issues faster, leading to more effective troubleshooting and resolution.
As an IT professional or a system administrator, I often need to check the event logs for debugging purposes. I used PowerShell to do this. In this tutorial, I will explain how to use PowerShell to query Windows Event Logs effectively.
What are Windows Event Logs?
Windows Event Logs are useful for diagnosing and troubleshooting system and application issues. They record significant occurrences on your computer, such as system errors, security events, and application logs. IT administrators can access and analyze these logs, which can help you identify and resolve issues promptly.
PowerShell provides different ways to interact with Windows Event Logs. It allows you to automate tasks, filter specific events, and generate reports. Unlike the Event Viewer, which is a graphical interface, PowerShell offers command-line access to Windows event logs.
Note: You need administrative privileges depending on the logs you want to access.
Using Get-EventLog
The Get-EventLog
cmdlet is the primary command used to retrieve event logs in PowerShell. Here’s a simple example to get you started:
Get-EventLog -LogName Application -Newest 10
This command retrieves the ten most recent entries from the Application log.
Here is the exact output in the screenshot below after I executed the above PowerShell script.
Check out Retrieve Your Windows Product Key Using PowerShell
Query Specific Event Logs using PowerShell
Now, let me show you how to query specific event logs using PowerShell.
Filtering by Event ID
Event IDs are unique identifiers for specific types of events. You can filter logs by event ID to find particular events. For example, to find events with ID 1000 in the Application log, you can use the cmdlet below.
Get-EventLog -LogName Application -InstanceId 1000
Filtering by Date Range
You can also filter Windows event logs by date range using powerShell. This is particularly useful when you need to investigate events that occurred within a specific timeframe. For example, to find events from the last 24 hours:
Get-EventLog -LogName System -After (Get-Date).AddDays(-1)
Here is the exact output in the screenshot below:
Read Enable WinRM (Windows Remote Management) Using PowerShell
Combine Filters
You can combine multiple filters to narrow down your search. For instance, to find events with ID 4624 (successful logon) in the Security log from the last week, here is the complete cmdlet.
Get-EventLog -LogName Security -InstanceId 4624 -After (Get-Date).AddDays(-7)
Exporting Event Logs
Exporting Windows event logs to a file can be useful for further analysis or archiving. You can export logs to various formats, such as CSV or XML. Here’s how to export logs to a CSV file using the below PowerShell script.
Get-EventLog -LogName Application -Newest 100 | Export-Csv -Path "C:\Logs\ApplicationLogs.csv" -NoTypeInformation
Parsing Event Logs
Sometimes, you need to extract specific information from event logs. PowerShell allows you to parse logs and extract relevant data. For example, to get the message and timestamp of recent errors in the System log:
Get-EventLog -LogName System -EntryType Error -Newest 50 | Select-Object TimeGenerated, Message
Read Get Windows Services Using PowerShell
Monitoring Event Logs in Real-Time
Real-time monitoring of event logs can help you detect and respond to issues as they occur. You can use the -Wait
parameter with the Get-WinEvent
cmdlet to achieve this:
Get-WinEvent -LogName Application -MaxEvents 1 -Wait
This command waits for new events in the Application log and displays them as they occur.
Read Get Windows Activation Status Using PowerShell
Windows Event Logs: Practical Use Cases
Now, let me show you some practical use cases where I have used PowerShell to work with Windows event logs.
Troubleshooting Application Crashes
Suppose you are an IT administrator in New York City, and users report that a critical application is crashing frequently. You can use PowerShell to find relevant events in the Application log:
Get-EventLog -LogName Application -EntryType Error -Newest 100 | Where-Object { $_.Source -eq "YourApplicationName" }
This command filters the 100 most recent error events related to the specified application.
Security Auditing
As a system administrator in Los Angeles, you might need to audit successful and failed logons for security purposes. You can use the following command to retrieve logon events from the Security log:
Get-EventLog -LogName Security -InstanceId 4624, 4625 -After (Get-Date).AddDays(-7)
Event ID 4624 represents successful logons, and 4625 represents failed logons.
Check out Get the Windows Version Using PowerShell
System Health Monitoring
For system health monitoring in a data center in San Francisco, you can use PowerShell to check for critical system events:
Get-EventLog -LogName System -EntryType Error, Warning -Newest 200
This command retrieves the 200 most recent error and warning events from the System log.
Conclusion
You can use PowerShell to query Windows Event Logs to manage and analyze log data. By using cmdlets like Get-EventLog
and Get-WinEvent
, you can get Windows event logs, filter specific events, and generate detailed reports.
In this tutorial, I explained how to get Windows event logs using PowerShell.
You may also like the following tutorials:
- Find Logged In User Using PowerShell
- Enable Remote Desktop Using PowerShell
- Find Installed Software Using PowerShell
- Create a Self-Signed Certificate Using PowerShell
- Create Desktop Shortcuts with Custom Icons Using PowerShell
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.
Post Date:
– Last Modified:
In this post, we will explore how to use PowerShell to view event logs. We will use the Get-EventLog
command to accomplish this, listing event types available and then show recent events.
1. List Available Event Log Types
To display all event log types on a system, run Get-EventLog -List
as shown below:
# Get event types PowerShell Get-EventLog -List
This command returns event categories such as System, Security, and Application. You can then specify a particular log type using the -LogName
parameter in subsequent commands.
2. Get Most Recent Events
To retrieve the 100 most recent events from the System log, run the following:
# Get most recent Windows events PowerShell Get-EventLog -LogName System -Newest 100
For a high-level view of frequent errors, group and count the newest 1000 error events from the Application log:
# Get most recent application events by count Get-EventLog -LogName Application -Newest 1000 -EntryType Error | Group-Object -Property Source -NoElement | Sort-Object -Property Count -Descending
This reveals recurring error sources, helping identify persistent issues.
3. Get Events Between Specific Dates
To retrieve critical and error events within a date range, use the Get-WinEvent
cmdlet in a PowerShell script:
param( [DateTime]$StartDate, [DateTime]$EndDate ) # Get all critical and error events from the Windows event logs Get-WinEvent -FilterHashtable @{ LogName = 'System, Application'; Level = 1, 2; StartTime = $StartDate; EndTime = $EndDate }
Replace START_DATE
and END_DATE
with your desired date range:
.\Get-CriticalAndErrorEvents.ps1 -StartDate '2021-01-01' -EndDate '2021-12-31'
This script filters events by:
– Date Range: Defined by your start and end dates
– Log Name: System and Application logs
– Level: Critical (1) and Error (2) events
Using PowerShell to explore and filter event logs offers a powerful way to troubleshoot and monitor system health. These commands and scripts will help you pinpoint issues and understand system behavior more effectively. Hope all this helps!