Очистка журналов событий event viewer в windows

В Windows вы можете очистить журналы событий Event Viewer с помощью графической оснастки eventvwr.msc, из командной строки и с помощью PowerShell.

Краткая заметка о том, как выполняет выгрузка журналов событий в PowerShell. Дополнительно я привел способ того, как можно изменить критерии выгрузки.

Скрипт для выгрузке довольно прост. Пример скрипта, который выгружает все критические события и ошибки из журнала приложений за последние 30 дней:

Основная логика находится в условиях фильтрации поиска – переменной $xmlQuery. Это ничто иное, как xml представление критериев поиска. Его можно получить непосредственно и Event Viewer. Для этого настройте критерии фильтрации нужного вам журнала на вкладке “Фильтр”.

Очистка журналов событий event viewer в windows

Затем перейдите на вкладку “XML”:

Очистка журналов событий event viewer в windows

Текст в основной секции окна и будет текстом, который необходимо передать в переменную $xmlQuery.

Пример выгруженного журнала и немного структурированного средствами Excel:

Очистка журналов событий event viewer в windows

Analyzing Windows Event Logs is an important part in SOC Operations and by continuously monitoring and analyzing logs, SOC analysts can identify a threat. It can also help the IR team to reconstruct the chain of events that lead to the attack.

Get-WinEvent is a powershell Cmdlet that allows us to view, filter and analyze windows event logs files. Windows Event Logs can also be viewed and filtered using Windows EventViewer, then whats the benefit of using Get-WinEvent? The answer to this is that it allows us to automate certain tasks and write scripts, such as finding event logs with certain properties in more then one event log files etc. Now lets get to using Get-WinEvent to perform certain tasks on Event Log Files:

Viewing the list of available windows event log file names which contains windows event logs:

Here, we are specifying to list all the logs ( -Listlog * ) in with the logs are greater then 0 (RecordCount -gt 0).

Viewing Event logs with Excessive Failed Logins:

Here we used -FilterHashtable to pass the parameters in key value pair. We looked for Event Id 4625 in Security logs, this event id represents failed logins.

Looking For A Service Created At A Specific Date:

Here, two variables are creating specifying the starting date from which we want the logs and the ending date. Then we are looking for Event ID 7045 which specifies service creation. Often services are used by adversaries for persistence and other malicious activities.

:/>  Разрешить этому приложению вносить изменения на вашем устройстве: как отключить это уведомление? |

Looking For A Suspicious Powershell Command Execution:

In the above command, we are searching for event id 4104 in which the message contains alphanumeric characters with length equal to or more then 150.

Hunting for Unsigned DLLs by Analyzing Event Logs:

Hunting for the loading of unsigned dlls can help us identify a dll related attack such as DLL Hijacking etc. Here event id 7 is a sysmon event related to image loading.

Event ID 7 (Image loaded): Important in detecting DLL Hijacking. This event is disabled by default and the sysmon-config file has to be edited to enable logging of this event.

The command enables us to look in the event log file for event id 7 in which the 12th property of the event equals false. The 12th property of the event here tells if the dll is signed or not. If not signed, it is equal to false.

Hunting for Credential Dumping Attack by Analyzing Event Logs:

In the above command, we searched for events with Event ID 10 in which the 8th property (which specifies the target process) is lsass.exe.

To conclude, Get-WinEvent proves to be great cmdlet provided by default that can help us analyze and filter various windows event logs using powershell to hunt for threats or to monitor for various events. This is just an introduction to using Get-WinEvent for event log analysis and much more can be done using it.

I am trying to use powershell to look through event logs that have specific IP addresses in the message property. More specifically, I set auditpol to log Windows Firewall events to the Windows Security log and view them in Event Viewer. It would be faster if I could filter via PowerShell for the events with the IP I’m looking for. I’ve mainly been working in PowerShell ISE.

$PSVersionTable

Name Value
—- —–
PSVersion 5.1.17763.5458

Here is the auditpol commands I use to get the Windows Firewall events to the Security log:

In event viewer, I filter for a specific time frame that my test takes place in, and for those event IDs, and I can use find to search for the IP I’m looking for. In this case, lets say the IP is 10.10.7.94. I can see this IP in Event Viewer by using Find. I go back to the filter and get the syntax from the XML tab as a beginning for my XML query. This is the syntax that got me closest to what I want (max events just to speed up testing):

:/>  Windows: TaskKill - Убить Процесс по PID, Имени, Порту - CMD - ShellHacks

This returns some events, but they do not contain the IP address I specified. An example of the message output I get returned is here:

Message : The Windows Filtering Platform has permitted a connection.

Application Information:
Process ID: 3752
Application Name: deviceharddiskvolume4windowssystem32dns.exe

Network Information:
Direction: Inbound
Source Address: 10.10.7.60
Source Port: 40536
Destination Address: 10.10.7.3
Destination Port: 53
Protocol: 17

Filter Information:
Filter Run-Time ID: 674097
Layer Name: Receive/Accept
Layer Run-Time ID: 44

Variations I’ve tried:
Not using the string casting (this doesn’t return results at all)
Single and double quotes around the IP address in the variable (this doesn’t return results at all)
Not using a variable and putting the IP directly in the where filter (this doesn’t return results at all)
Use the “contains” operator instead of “like” (this doesn’t return results at all)

What am I missing? Any help would be greatly appreciated.

As far as I can tell, there is no memory leak:

Here’s sample output from running the above in Windows PowerShell on Windows 11 (22H2), showing no long-term growth of memory usage:

CallCount Memory Use (Working Set, MB)
——— —————————-
0 83.23
500 85.82
1000 85.83
1500 84.86
2000 84.79
2500 85.05
3000 84.84
3500 84.88
4000 84.87
4500 84.91
5000 84.98
5500 84.95
6000 84.90
6500 84.91
7000 84.89
7500 84.88
8000 84.93
8500 84.95
9000 84.88
9500 84.98
10000 84.93
10500 84.90
11000 84.88
11500 84.98
12000 84.88
12500 84.93
13000 84.89
13500 85.04
14000 84.93
14500 84.99
15000 84.89
15500 84.86
16000 84.94
16500 84.96
17000 84.93
17500 84.95
18000 84.89
18500 84.89
19000 84.86
19500 84.89
20000 84.84
20500 84.89

Команда PowerShell для очистки журналов событий

В PowerShell для получения списка журналов событий Windows и их очистки можно использовать командлеты Get-WinEvent и Clear-EventLog.

:/>  Как увеличить яркость экрана на Виндовс 10 - 8 способов

Откройте консоль PowerShell с правами администратора, выведите список всех имен журналов в Windows и их настройки:

Get-WinEvent -ListLog *

Очистка журналов событий event viewer в windows

Команда выведет максимальные размеры и параметры всех журналов событий Windows.

Чтобы удалить все события из двух журналов (например, журналов Security и System), выполните команду:

Clear-EventLog –LogName Security,System

При этом журнал очищается, и в него записывается событие с EventID 104 или 1102 с временем очистки, пользователем, выполнившим и описанием:

The System log file was cleared
The audit log was cleared.

Очистка журналов событий event viewer в windows

Для очистки административных и операционных журналов событий Windows, выполните такую однострочную команду PowerShell:

Примечание. В нашем примере не удалось очистить 3 журнала из-за ошибки доступа. Попробуйте вручную очистить содержимое этих журналов из консоли Event Viewer.

Очистка журналов событий event viewer в windows

Удаление логов Windows из командной строки

Для очистки журналов Windows из командной строки используется утилита wevtutil.exe.

Вывести список зарегистрированных в Windows журналов событий:

или короткий вариант:

Для удаления событий из одного конкретного журнала, скопируйте его имя и выполните команду:

WevtUtil cl Microsoft-Windows-GroupPolicy/Operational

Перед очисткой можно создать резервную копию событий в журнале в отдельный файл:

WevtUtil cl Microsoft-Windows-GroupPolicy/Operational /bu:GPOLOG_Bak.evtx

Можно очистить сразу все журналы событий из cmd.exe:

for /F “tokens=*” %1 in (‘wevtutil.exe el’) DO wevtutil.exe cl “%1”

Для BAT файла нужно использовать немного другой синтаксис:

for /F “tokens=*” %%1 in (‘wevtutil.exe el’) DO wevtutil.exe cl “%%1”

Очистка журнал событий из графической консоли Event Viewer

Самый интуитивный способ очистки журналов событий Windows – воспользоваться графической консоль Event Viewer.

Такой способ позволяет быстро удалить все события из одного конкретного журнала. Однако в Windows используется несколько сотен журналов для разных компонентов операционной системы и стороннего ПО.

По умолчанию Windows хранит журналы в файлах с расширением EVTX в каталоге
%SystemRoot%System32WinevtLogs
.

Если вам нужно очистить их все – это будет утомительно вручную прощелкать все разделы Event Viewer и очистить каждый журнал. В этом случае для удаления событий лучше использовать PowerShell или командную строку.