In this article…
- What is the Windows Event Log (EventLog) service?
- What happens if I stop EventLog?
- Is it OK to disable the Windows Event Log service?
- Questions? Problems?
What is the Windows Event Log (EventLog) service?
The EventLog service manages event logs — repositories of events generated by services, scheduled tasks and applications working closely with the Windows operating system.
The service’s display name is Windows Event Log and it runs inside the service host process, svchost.exe. By default, the service is set to start automatically when your computer boots:
You can use the Windows Event Viewer to browse the event logs managed by the service. For example, here are some of the records captured in the Windows Security event log:
What happens if I stop EventLog?
You may find it virtually impossible to stop the Windows Event Log service.
That’s because the service supports several important system services. You can see that list on the service’s Dependencies tab:
And because of those dependency relationships, attempting to stop EventLog triggers a “cascade” that causes all dependent services to stop too. Here you can see Windows alerting us of that situation:
But after we clicked “Yes”, Windows failed to stop EventLog and the dependent services! A peculiar error was returned:
We tracked the issue to “Network List Service” (netprofm). That service refused every attempt to stop it, consistently failing with the error above. And since we could not stop “Network List Service”, we could not stop EventLog either.
Is it OK to disable the Windows Event Log service?
No — it’s not safe to disable the Windows Event Log service.
Indeed, in the very description of the service, Microsoft warns:
Stopping this service may compromise security and reliability of the system.
That advice makes sense because EventLog provides essential support for Windows Services, scheduled tasks, and other background programs. Those components typically run “headless”, without a user interface, and rely on the event logs to record important events.
If the EventLog service stops, those background components will have no way to chronicle their activities. There would be an ominous gap in the operating system’s low-level records.
With that in mind, it’s easy to see why the EventLog service is an alluring target for attackers looking to compromise a system. Once the service has been crippled, vital forensics records may not be captured and intruders could operate with impunity.
Questions? Problems?
If you would like to know more about the Windows Event Log service, or you have a specific problem, please feel free to get in touch. We will do our best to help you!
You may also like…
Время на прочтение5 мин
Количество просмотров79K
Пользовательская рабочая станция — самое уязвимое место инфраструктуры по части информационной безопасности. Пользователям может прийти на рабочую почту письмо вроде бы из безопасного источника, но со ссылкой на заражённый сайт. Возможно, кто-то скачает полезную для работы утилиту из неизвестно какого места. Да можно придумать не один десяток кейсов, как через пользователей вредоносное ПО может внедриться на внутрикорпоративные ресурсы. Поэтому рабочие станции требуют повышенного внимания, и в статье мы расскажем, откуда и какие события брать для отслеживания атак.
Для выявления атаки на самой ранней стадии в ОС Windows есть три полезных событийных источника: журнал событий безопасности, журнал системного мониторинга и журналы Power Shell.
Журнал событий безопасности (Security Log)
Это главное место хранения системных логов безопасности. Сюда складываются события входа/выхода пользователей, доступа к объектам, изменения политик и других активностей, связанных с безопасностью. Разумеется, если настроена соответствующая политика.
Перебор пользователей и групп (события 4798 и 4799). Вредоносное ПО в самом начале атаки часто перебирает локальные учетные записи пользователей и локальные группы на рабочей станции, чтобы найти учетные данные для своих тёмных делишек. Эти события помогут обнаружить вредоносный код раньше, чем он двинется дальше и, используя собранные данные, распространится на другие системы.
Создание локальной учётной записи и изменения в локальных группах (события 4720, 4722–4726, 4738, 4740, 4767, 4780, 4781, 4794, 5376 и 5377). Атака может также начинаться, например, с добавления нового пользователя в группу локальных администраторов.
Попытки входа с локальной учётной записью (событие 4624). Добропорядочные пользователи заходят с доменной учётной записью и выявление входа под локальной учётной записью может означать начало атаки. Событие 4624 включает также входы под доменной учетной записью, поэтому при обработке событий нужно зафильтровать события, в которых домен отличается от имени рабочей станции.
Попытка входа с заданной учётной записью (событие 4648). Такое бывает, когда процесс выполняется в режиме “Запуск от имени” (run as). В нормальном режиме работы систем такого не должно быть, поэтому такие события должны находиться под контролем.
Блокировка/разблокировка рабочей станции (события 4800-4803). К категории подозрительных событий можно отнести любые действия, которые происходили на заблокированной рабочей станции.
Изменения конфигурации файрволла (события 4944-4958). Очевидно, что при установке нового ПО настройки конфигурации файрволла могут меняться, что вызовет ложные срабатывания. Контролировать такие изменения в большинстве случаев нет необходимости, но знать о них точно лишним не будет.
Подключение устройств Plug’n’play (событие 6416 и только для WIndows 10). За этим важно следить, если пользователи обычно не подключают новые устройства к рабочей станции, а тут вдруг раз — и подключили.
Windows включает в себя 9 категорий аудита и 50 субкатегорий для тонкой настройки. Минимальный набор субкатегорий, который стоит включить в настройках:
Logon/Logoff
- Logon;
- Logoff;
- Account Lockout;
- Other Logon/Logoff Events.
Account Management
- User Account Management;
- Security Group Management.
Policy Change
- Audit Policy Change;
- Authentication Policy Change;
- Authorization Policy Change.
Системный монитор (Sysmon)
Sysmon — встроенная в Windows утилита, которая умеет записывать события в системный журнал. Обычно требуется его устанавливать отдельно.
Эти же события можно в принципе найти в журнале безопасности (включив нужную политику аудита), но Sysmon даёт больше подробностей. Какие события можно забирать из Sysmon?
Создание процесса (ID события 1). Системный журнал событий безопасности тоже может сказать, когда запустился какой-нибудь *.exe и даже покажет его имя и путь запуска. Но в отличие от Sysmon не сможет показать хэш приложения. Злонамеренное ПО может называться даже безобидным notepad.exe, но именно хэш выведет его на чистую воду.
Сетевые подключения (ID события 3). Очевидно, что сетевых подключений много, и за всеми не уследить. Но важно учитывать, что Sysmon в отличие от того же Security Log умеет привязать сетевое подключение к полям ProcessID и ProcessGUID, показывает порт и IP-адреса источника и приёмника.
Изменения в системном реестре (ID события 12-14). Самый простой способ добавить себя в автозапуск — прописаться в реестре. Security Log это умеет, но Sysmon показывает, кто внёс изменения, когда, откуда, process ID и предыдущее значение ключа.
Создание файла (ID события 11). Sysmon, в отличие от Security Log, покажет не только расположение файла, но и его имя. Понятно, что за всем не уследишь, но можно же проводить аудит определённых директорий.
А теперь то, чего в политиках Security Log нет, но есть в Sysmon:
Изменение времени создания файла (ID события 2). Некоторое вредоносное ПО может подменять дату создания файла для его скрытия из отчётов с недавно созданными файлами.
Загрузка драйверов и динамических библиотек (ID событий 6-7). Отслеживание загрузки в память DLL и драйверов устройств, проверка цифровой подписи и её валидности.
Создание потока в выполняющемся процессе (ID события 8). Один из видов атаки, за которым тоже нужно следить.
События RawAccessRead (ID события 9). Операции чтения с диска при помощи “\\.\”. В абсолютном большинстве случаев такая активность должна считаться ненормальной.
Создание именованного файлового потока (ID события 15). Событие регистрируется, когда создается именованный файловый поток, который генерирует события с хэшем содержимого файла.
Создание named pipe и подключения (ID события 17-18). Отслеживание вредоносного кода, который коммуницирует с другими компонентами через named pipe.
Активность по WMI (ID события 19). Регистрация событий, которые генерируются при обращении к системе по протоколу WMI.
Для защиты самого Sysmon нужно отслеживать события с ID 4 (остановка и запуск Sysmon) и ID 16 (изменение конфигурации Sysmon).
Журналы Power Shell
Power Shell — мощный инструмент управления Windows-инфраструктурой, поэтому велики шансы, что атакующий выберет именно его. Для получения данных о событиях Power Shell можно использовать два источника: Windows PowerShell log и Microsoft-WindowsPowerShell / Operational log.
Windows PowerShell log
Загружен поставщик данных (ID события 600). Поставщики PowerShell — это программы, которые служат источником данных для PowerShell для просмотра и управления ими. Например, встроенными поставщиками могут быть переменные среды Windows или системный реестр. За появлением новых поставщиков нужно следить, чтобы вовремя выявить злонамеренную активность. Например, если видите, что среди поставщиков появился WSMan, значит был начат удаленный сеанс PowerShell.
Microsoft-WindowsPowerShell / Operational log (или MicrosoftWindows-PowerShellCore / Operational в PowerShell 6)
Журналирование модулей (ID события 4103). В событиях хранится информация о каждой выполненной команде и параметрах, с которыми она вызывалась.
Журналирование блокировки скриптов (ID события 4104). Журналирование блокировки скриптов показывает каждый выполненный блок кода PowerShell. Даже если злоумышленник попытается скрыть команду, этот тип события покажет фактически выполненную команду PowerShell. Ещё в этом типе события могут фиксироваться некоторые выполняемые низкоуровневые вызовы API, эти события обычно записывается как Verbose, но если подозрительная команда или сценарий используются в блоке кода, он будет зарегистрирован как c критичностью Warning.
Обратите внимание, что после настройки инструмента сбора и анализа этих событий потребуется дополнительное время на отладку для снижения количества ложных срабатываний.
Расскажите в комментариях, какие собираете логи для аудита информационной безопасности и какие инструменты для этого используете. Одно из наших направлений — решения для аудита событий информационной безопасности. Для решения задачи сбора и анализа логов можем предложить присмотреться к Quest InTrust, который умеет сжимать хранящиеся данные с коэффициентом 20:1, а один его установленный экземпляр способен обрабатывать до 60000 событий в секунду из 10000 источников.
If you’re using a Windows server and want to know what happened to your machine, Windows logs are an essential resource. Windows logs record various system activities, errors, and other significant events, providing valuable information for troubleshooting, auditing, and ensuring system integrity. Understanding how to access, interpret, and utilise these logs enables efficient, problem solving, enables security measures and ensures the smooth operation of your system.
In this guide, you will learn about Windows event logs, its different categories, how to filter and create Custom Views.
What is a Windows Event Log?
A Windows event log is a file that keeps track of system events and errors, application issues, and security events. Windows Event log can also provide insights into an application’s behavior by tracking its interactions with other processes and services. With the right knowledge of the information stored in these logs, you can easily diagnose and easily resolve issues within your system and applications.
You can access the windows events logs as follows:
Using the Start Menu:
- Click on the Start button or press the Windows key.
- Type
Event Viewer
in the search box and select it from the search results.
Using the Run Dialog:
- Press
Windows + R
to open the Run dialog. - Type
eventvwr
and press Enter.
Using the Control Panel:
- Open the Command Prompt and run as administrator.
- Type
eventvwr
and press Enter.
You can see the detailed steps below. Now let’s discuss and understand windows events logs in detail.
Understanding Windows Event Logs categories & Types
There are different Windows logs, each serving a specific purpose in tracking and recording events related to your system, applications, and security. They include:
- System Events: System events log information is about the core operations of your Windows operating system. System events are essential for maintaining your system’s health and functionality because it records events related to the system’s hardware and software components. Some system events are as follows:
- Hardware Failures: Logs any issues related to hardware components, such as disc failures or memory errors.
- Driver Issues: Records events related to the loading, unloading, or malfunctioning of device drivers. This helps in identifying driver-related problems that could affect system stability.
- System Startups and Shutdowns: Tracks the times when the system starts up or shuts down. This can be useful for understanding system uptime and diagnosing issues related to improper shutdowns or startup failures.
- Application Events: Data related to software applications running on the system includes application errors, warnings, and informational messages. If you are using a Windows server to run your production-level application, you can use the application errors, warnings, and messages provided here to solve the issue. There are different types of Application events some are as follows:
- Application Errors: Application errors are events generated by software applications when they encounter issues that prevent them from functioning correctly.
- Warnings: Logs warnings from applications about potential issues that might not be critical but could lead to problems if not addressed.
- Informational Messages: Provides general information about application activities, such as successful operations or status updates, helping to understand the normal functioning of applications.
- Security Events: Security events are logs that capture all security-related activities on your Windows system. They are essential for monitoring, maintaining, and auditing the security of your system. These events help detect unauthorised access attempts, monitor access to sensitive resources, and track changes to system policies. Some security events are as follows:
- Successful and Failed Login Attempts: Successful and failed login attempts are critical events that are logged by a system to monitor access and ensure security. These logs provide valuable insights into user activity, helping to detect unauthorised access attempts and identify potential security threats.
- Resource Access: These events log attempts to access protected resources such as files, folders, or system settings. Monitoring these logs ensures that sensitive data is accessed appropriately and helps identify unauthorised access attempts.
- System Policy Changes: These logs record any changes to system policies, including modifications to user permissions or security settings. This is important for auditing purposes and ensuring compliance with security policies, helping to maintain the integrity and security of the system.
- Setup Events: Setup events are logs that contain detailed information about the installation and setup processes on your Windows system. These logs are valuable for diagnosing and resolving issues that occur during the installation or configuration of software and system components. Some Setup events are as follows:
- Installation Processes: Installation processes refer to the series of steps and operations carried out to install software, updates, or system components on a Windows system. It contains log details about software installation, updates, or system components. This helps in diagnosing issues related to incomplete or failed installations.
- Setup Configurations: Records information about system configurations during the setup process. This can be useful for understanding your system’s initial setup and configuration.
- Forwarded Events: Forwarded events are logs sent from other computers to a centralised logging server. This is particularly useful in larger environments where centralised log management is needed. They include:
- Logs from Remote Systems: Collects event logs from multiple systems, allowing for centralised monitoring and management.
- Centralised Logging Scenarios: Useful for organisations that need to aggregate logs from various systems to a single location for easier analysis and monitoring.
Accessing the Windows Event Viewer
Windows Event Viewer is a Windows application that lets you see your computer’s logs, warnings, and other events. Each application you open generates entries that are recorded in an activity log, which can be viewed from the Event Viewer.
There are several ways to access the Windows Event Viewer. Here are some of them:
-
Using the Start Menu:
- Click on the Start button or press the Windows key.
- Type
Event Viewer
in the search box.
Using start menu to open Event viewer — Select Event Viewer from the search results which will popup something like this.
Event Viewer main page 2. Using the Run Dialog: — Press
Windows + R
to open the Run dialog. — Typeeventvwr
and press Enter.Windows Run App to open Event Viewer Windows Event viewer landing page 3. Using Control Panel: — Open the Command Prompt and run as administrator
Open CMD as Administrator from start menu — Once open, type
eventvwr
and press enter, and you will be redirected to Event Viewer page.CMD terminal
Windows Log Location
Windows event logs are stored in files located in the C:\\Windows\\System32\\winevt\\Logs
directory. Each log file corresponds to a specific log category, such as System, Application, or Security. It may differ depending on which version of Windows you are using.
The main event log files are:
- Application.evtx: Logs events from applications and programs.
- Security.evtx: Logs security events like successful or failed logins.
- System.evtx: Logs events related to Windows system components and drivers
You can find many other log files which could be related to system operations & other processes that are happening inside the Windows System. Windows 11uses the .evtx
format rather than using the classic EVT
format.
Understanding Event Viewer Entries
Event Viewer entries provide detailed information about each logged event. It is like a log book for your Windows system. They record important happenings within the system, including applications, systems, security, failed events, etc. Understanding these entries is key to effective log management.
The key components of an Event Viewer entry are:
- Date and Time: When the event occurred.
- Source: The application or system component that generated the event.
- Event ID: A unique identifier for the event type.
- Level: The severity of the event (Information, Warning, Error, Critical).
- User: The user account under which the event occurred.
- Computer: The name of the computer where the event was logged.
- Description: Detailed information about the event.
Each event in the Event Viewer has a severity level, indicating the importance and type of the event:
- Information (Green Light): These events resemble a green traffic light, signifying smooth sailing. They indicate successful operations or occurrences within your system.
- Warning (Yellow Light): Treat these entries with caution, like a yellow traffic light. They signal potential issues that warrant attention but might not cause immediate problems.
- Error (Orange Light): Think of error entries as an orange traffic light; proceed with care. They denote significant problems that could affect system functionality. Imagine an error message indicating a driver failure.
- Critical (Red Light): Critical entries are akin to a red traffic light; stop and address the situation immediately. They represent severe errors that have caused a major failure. A critical event might report a complete system shutdown or a critical service crashing.
Filtering and Custom Views
Event Viewer allows you to filter events using a variety of parameters, including date, event level, source, and more. Consider the following scenario: your system exhibits weird behaviour, but the Event Viewer is overflowing with hundreds, if not thousands, of entries. Filtering steps and generating custom views can significantly reduce the workload. You may also construct custom views to focus on specific kinds of events:
- In the Event Viewer, you’ll see Administrative Events, to create special logs right-click on «Custom Views» and select «Create Custom View.»
1. In the Custom View page, you can see logged
drop down, choose a preferred time or it gives you an option to create a custom time to set. 2. On the Event Level choose an appropriate level for your custom view, You can choose among the 5 levels.
1. Once done, choose how you want the events to be filtered, By log
or By source
.
Once everything is set up according to your needs, save all events in Custom View as
from the drop-down menu and choose an appropriate location to save the logs. Click on the Save button. (A log file with the extension .evtx
will be saved on your device).
Conclusion
This blog provides an understanding how you can use the Windows Event Viewer which is provided by the Windows in default and using it to monitor Windows logs.
- Main event log files are stored in
C:\\Windows\\System32\\winevt\\Logs
. - Windows logs are crucial for understanding the activities, errors, and significant events on your machine. They provide valuable information for troubleshooting, auditing, and ensuring system integrity.
- They record a variety of system activities, errors, and other significant events, providing valuable information for troubleshooting, auditing, and ensuring system integrity.
- We learnt how to setup Filtering and Custom Views to optimise what we see and solve the problems and where it happened.
By grasping the significance of different event types such as System, Application, Security, Setup, and Forwarded Events, and knowing how to filter and export logs, you can effectively manage your Windows system.
FAQ’s
How to view Windows logs?
To view Windows logs, use the built-in Event Viewer:
- Press
Win + R
, typeeventvwr
, and press Enter. - Navigate through the console tree to find the log you want to view (e.g., Windows Logs > Application).
Where are Microsoft logs?
Microsoft logs, including Windows logs, can be found in the Event Viewer under sections like Application, Security, and System. Log files are also located in the C:\Windows\System32\winevt\Logs
directory.
How do I audit Windows logs?
To audit Windows logs:
- Open Event Viewer.
- Navigate to Security logs under Windows Logs.
- Configure auditing policies via the Local Security Policy or Group Policy Management Console.
How do I check my Windows activity log
Check your Windows activity log by viewing the Security logs in Event Viewer. These logs record user logins, logoffs, and other security-related activities.
Which is Windows log key?
The Windows log key, often referred to as the Windows key, is the key on your keyboard with the Windows logo. It is used in various shortcuts to open system tools, including Event Viewer (Win + X
> Event Viewer).
Where is the logs folder?
The logs folder is located at C:\Windows\System32\winevt\Logs
. This folder contains all the event log files in .evtx format.
Why are Windows logs important?
Windows logs are important because they provide detailed information about system operations, security events, and application behavior, which is crucial for troubleshooting, auditing, and ensuring system integrity.
How to view log files?
View log files using Event Viewer:
- Open Event Viewer (
Win + R
, typeeventvwr
, press Enter). - Expand the Windows Logs section and select the log you want to view.
Where are login logs?
Login logs are located in the Security logs section of Event Viewer. They record all login attempts, both successful and failed.
What are system logs?
System logs contain information about the core operations of the Windows operating system, including hardware events, driver issues, and system startups and shutdowns. They are found under the System section in Event Viewer.
How do I find Windows log files?
Find Windows log files in the Event Viewer or directly in the C:\Windows\System32\winevt\Logs
directory.
How do I view user logs in Windows 10?
View user logs in Windows 10 through the Event Viewer:
- Open Event Viewer.
- Go to Windows Logs > Security to see logs related to user activities, including logins and logoffs.
How do I view Windows setup logs?
To view Windows setup logs:
- Open Event Viewer.
- Navigate to Applications and Services Logs > Microsoft > Windows > Setup.
How do I view Windows app logs?
To view Windows application logs:
- Open Event Viewer.
- Navigate to Windows Logs > Application to see logs related to software applications running on your system.
Was this page helpful?
Журнал событий 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}
}