Журнал событий windows cmd

on August 15, 2010

We can open event viewer console from command prompt or from Run window by running the command eventvwr.  To retrieve the events information from log files in command line we can use eventquery.vbs. This file can be found in the directory C:\Windows\System32.

Using eventquery.vbs we can dump the events selectively based on various parameters. These parameters include event source, event id, event date, event type(information, error , warning), event log file name(system, application, security, IE etc). Below are few examples on how to use this script file.

To list all the events that are created by a particular service/application.

cscript eventquery.vbs /FI "source eq source_name"

For example to list all the events that are created by DHCP you can run the below command.

cscript eventquery.vbs /FI "source eq dhcp"

To list all the events originated from Outlook:

cscript eventquery.vbs /FI "source eq outlook"

To list the events with a specific id.

cscript eventquery.vbs /FI "id eq id_number"

To list application events that have occurred after a specific time

cscript.exe eventquery.vbs /FI "DateTime gt 11/13/2010,01:00:00AM"

To print all warning events from application log file:

cscript eventquery.vbs /L application /FI "type eq warning"

To dump all the error events generated by a particular user:

cscript eventquery.vbs /FI "user eq domainname\username" /FI "type eq error"

This script is not supported in Windows 7.

Для различных событий и ошибок системы и приложений Windows ведёт журналы событий, которые можно просмотреть и получить дополнительную информацию, которая может быть полезной при решении проблем с компьютером.

В этой инструкции для начинающих — способы открыть просмотр событий Windows 11/10 и дополнительная информация на тему, которая может пригодиться. На близкую тему: Как отключить журнал событий в Windows.

Контекстное меню кнопки Пуск и поиск

Самый быстрый способ перейти к просмотру журналов событий в Windows 11 и 10 — нажать правой кнопкой мыши по кнопке «Пуск» или нажать клавиши Win+X на клавиатуре и выбрать пункт «Просмотр событий» в открывшемся меню.

Журнал событий в контекстном меню кнопки Пуск

Ещё один простой и в большинстве случаев работающий способ открыть какой-либо системный инструмент, расположение которого вам неизвестно — использовать поиск в панели задач.

Начните вводить «Просмотр событий» в поиске, после чего запустите найденный результат:

Просмотр событий в поиске Windows

Почему не «Журнал событий» или «Журнал ошибок», которые пользователи обычно ищут? Причина в том, что сами журналы — это файлы на диске в папках

C:\Windows\System32\winevt\Logs
C:\Windows\System32\LogFiles

Пользователи, задавая вопрос о том, где журнал событий в Windows, обычно имеют в виду именно системный инструмент «Просмотр событий» для удобного просмотра соответствующих журналов.

Команда «Выполнить»

Самый быстрый и часто используемый метод запуска просмотра журналов событий Windows — использование команды «Выполнить»:

  1. Нажмите клавиши Win+R на клавиатуре, либо нажмите правой кнопкой мыши по кнопке «Пуск» и выберите пункт «Выполнить».
  2. Введите eventvwr.msc (или просто eventvwr) и нажмите Enter.
    Запуск просмотра событий командой

  3. Откроется «Просмотр событий».

Эту же команду можно использовать для создания ярлыка или для открытия журнала событий в командной строке. Возможно, вам пригодится информация о других полезных командах «Выполнить».

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

Помимо просмотра журнала событий, в Windows присутствует ещё один полезный инструмент — Монитор стабильности системы, позволяющий наглядно получить информацию о работе вашей системы по дням на основании данных из журнала событий.

Вместо использования текстовых лог файлов в скриптах, можно записывать информации о событиях непосредственно в журналы Event Viewer. В этой статье мы рассмотрим, как записывать логи в журналы событий Windows из скрипта PowerShell или из командной строки.

Для записи информации в журнал событий используется командлет Write-EventLog. Например, что записать информационного событие в журнал Application, выполните:

Write-EventLog -LogName Application -Source "Application" -EntryType Information -EventID 1 -Message "PS1 Script started"

Можно добавить отдельный источник событий в существующий журнал:

New-EventLog -LogName Application -Source "MyScripts"

Теперь можно записывать события с собственным источником:

Write-EventLog -LogName Application -Source "MyScripts" -EntryType Warning –EventID 1 –Message "PS1 Script started"

Откройте консоль журнала событий (
eventvwr.msc
), разверните журнал Application и проверьте, что новое событие с вашим описанием было добавлено в лог.

Write-EventLog - записать событие в Event Viewer из PowerShell

В качестве типа события в EntryType можно указывать Error, Information, FailureAudit, SuccessAudit или Warning.

Если вы хотите добавить в журнал событие из BAT/CMD скрипта, нужно использовать команду eventcreate:

eventcreate /t information /l application /id 1 /d "BAT script started"

eventcreate - записать событие в журнал событий из командной строки

Можно создать для ваших логов отдельный журнал событий. Его можно создать с помощью команды New-EventLog.

New-EventLog -LogName CustomPSLog -source 'MyScripts','Function1','Function2','Function3'

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

If ([System.Diagnostics.EventLog]::SourceExists(‘CustomPSLog’) -eq $False) {
New-EventLog -LogName CustomPSLog -Source ….
}

Чтобы новый журнал появится в графической консоли Event Viewer, в него нужно отправить хотя бы одно событие:

Write-EventLog -LogName CustomPSLog -Source MyScripts -EntryType Information -EventID 1 -Message "Test"

Новый журнал появится в корне раздела Applications and Services Logs. Для файла журнала будет создан новый EVTX файл в папке
%SystemRoot%\System32\Winevt\Logs
.

Создать новый журнал событий в Event Viewer

Для поиска и фильтрации событий в журналах Event Viewer используется командлет Get-WinEvent. Вывести список последних событий в вашем журнале:

Get-WinEvent -FilterHashtable @{logname='CustomPSLog';id=1}|ft TimeCreated,Id,Message | Select-Object -First 5

Командлет Write-EventLog не поддерживается в новых версиях PowerShell Core. При запуске команды с ним появится ошибка:

Write-EventLog: The term 'Write-EventLog' is not recognized as a name of a cmdlet, function, script file, or executable program.

Вместо него в PowerShell Core 7.x нужно использовать New-WinEvent. Однако для его использования нужно регистрировать отдельный провайдер, что может вызвать затруднения. Гораздо проще в скриптах PowerShell Core сначала импортировать модуль Microsoft.PowerShell.Management с опцией -UseWindowsPowerShell. После этого в скрипте PowerShellCore можно использовать командлет Write-EventLog:

Import-Module Microsoft.PowerShell.Management -UseWindowsPowerShell
Write-EventLog -LogName CustomPSLog1 -Source CustomPSLog -EntryType Information -EventID 1 -Message "Test2"

Для записи в журналы событий Windows с помощью командлета Write-EventLog нужны права администратора. Под пользователем без прав администратора можно записать события только в кастомные журналы Event Viewer, созданные администратором.

The Command Prompt (cmd) can be used to access and manage the Event Viewer logs, allowing users to filter, display, or export events efficiently using specific commands.

Here’s an example command to display the last 10 entries from the System log:

wevtutil qe System /c:10

Understanding Event Viewer

What is Event Viewer?

Event Viewer is a Microsoft Management Console (MMC) application that lets users view and analyze the event logs on a Windows operating system. This tool is crucial for diagnosing issues, monitoring system performance, and auditing security. The application is a centralized logging system that records information about significant software and hardware events.

The Event Viewer includes several types of logs, such as:

  • System Logs: Contains events logged by Windows and its components.
  • Application Logs: Logs created by applications and services.
  • Security Logs: Provides a record of security-related events, such as logon attempts.

Why Use Event Viewer?

Monitoring system events is paramount for effective troubleshooting and system administration. The Event Viewer helps identify:

  • Errors and Warnings: These entries indicate system issues and misconfigurations that need attention.
  • Informational Events: Events that provide non-critical information about system operations.

Utilizing Event Viewer improves your understanding of the system behavior and enhances the ability to mitigate potential risks before they escalate into serious problems.

Mastering Cmd Net View: A Quick Guide to Network Discovery

Mastering Cmd Net View: A Quick Guide to Network Discovery

Accessing Event Viewer via CMD

Overview of Methods to Open Event Viewer

While Event Viewer can be accessed through the GUI, many advanced users prefer the flexibility and speed that CMD offers. Using the command line can also facilitate automation and scripting for administrative tasks.

How to Open Event Viewer from CMD

Using the `eventvwr` Command

To launch Event Viewer simply, you can use the following command:

eventvwr

This command opens the Event Viewer directly, giving you immediate access to the event logs without navigating through menus.

Using the `mmc` Command

For users who want to manage multiple components within the Microsoft Management Console, you can open Event Viewer with:

mmc eventvwr.msc

This command not only opens Event Viewer but also allows it to be used with other management tools, providing a centralized view for various system components.

Cmd Generator: Create Commands Effortlessly in Cmd

Cmd Generator: Create Commands Effortlessly in Cmd

Exploring the Event Logs in CMD

Navigating Windows Event Logs via CMD

Each type of log provides unique insights into system performance. Navigating through these logs can be accomplished through command-line tools, allowing you to quickly locate specific events.

Viewing Event Logs Using CMD

Using the `wevtutil` Command

The `wevtutil` command is a powerful utility that allows you to interact with event logs at a granular level. You can list all available logs by executing:

wevtutil el

This command will output a list of all event logs available on the system, including their status.

Mastering Cmd Winver: Quick Guide to Check Windows Version

Mastering Cmd Winver: Quick Guide to Check Windows Version

Filtering and Searching Logs

Filtering Events Using CMD

Filtering events can help you pinpoint specific issues. You can use `wevtutil` in combination with XPath querying to achieve this.

Using `wevtutil qe`

To query specific events, you can use the following command format, replacing `<logname>` and `XXXX` with the appropriate values:

wevtutil qe <logname> /q:"*[System[(EventID=XXXX)]]"

For example, to find errors in the Application log with Event ID 1000, you would use:

wevtutil qe Application /q:"*[System[(EventID=1000)]]"

This command efficiently filters the events, enabling you to focus on critical issues directly.

Searching for Specific Events

The ability to search for specific events using XPath provides immense power in diagnosing issues. XPath allows you to build complex queries to filter events based on multiple criteria, such as date ranges or specific event sources.

Mastering Cmd Printers: A Quick Guide

Mastering Cmd Printers: A Quick Guide

Exporting Event Logs

How to Export Logs to a File

Exporting event logs is essential for archiving and analysis. You can accomplish this with the `wevtutil` command.

Using `wevtutil epl`

To export an event log to a .evtx file, you can use the following command:

wevtutil epl <logname> <filename>.evtx

For instance, to export the Application log to a specific location, execute:

wevtutil epl Application C:\Logs\ApplicationLog.evtx

This command ensures logs are saved for future reference or further analysis.

Cmd Run Powershell: A Quick Command Guide

Cmd Run Powershell: A Quick Command Guide

Automating Event Log Monitoring

Scheduling Event Log Checks

Automating the monitoring of event logs can save significant time and ensure that no critical events are missed. By using Task Scheduler, you can schedule CMD scripts that periodically check specific event logs and alert you if particular conditions are met.

For instance, you might set up a task that runs a command to query for critical system errors every day and notifies you via email or logs the output to a file.

Cmd Cheat Sheet: Essential Commands at a Glance

Cmd Cheat Sheet: Essential Commands at a Glance

Common Issues and Troubleshooting

Potential Issues with Event Viewer in CMD

While interfacing with Event Viewer through CMD can be efficient, users may encounter certain issues. Common problems include:

  • Permissions Issues: Ensure you run CMD with administrative privileges to access certain logs, particularly security logs.
  • Syntax Errors: Always double-check command syntax as misspellings can lead to failures.

If you encounter any errors, consulting the official Microsoft documentation on `wevtutil` and event IDs can provide further insights into resolving these issues.

Mastering Cmd in Powershell: A Quick Guide

Mastering Cmd in Powershell: A Quick Guide

Conclusion

In this guide, we explored the capabilities of accessing and managing cmd event viewer for system administration. From opening the Event Viewer via various commands to filtering, querying, and exporting logs, CMD proves to be a valuable tool for enhancing your technical skills in system management. By practicing these commands, you can better troubleshoot and analyze the performance of Windows environments. Don’t hesitate to experiment with these commands and share your experiences or questions for further learning!

Mastering Cmd Set Variable: Quick Guide for Beginners

Mastering Cmd Set Variable: Quick Guide for Beginners

Additional Resources

For those looking to dive deeper into CMD and Event Viewer functionalities, consider exploring Microsoft’s official documentation. Being well-versed in both command-line tools and the graphical interfaces will bolster your skills in system administration and troubleshooting.

Event Viewer – How to Access the Windows 10 Activity Log

The Windows 10 Event Viewer is an app that shows a log detailing information about significant events on your computer. This information includes automatically downloaded updates, errors, and warnings.

In this article, you’ll learn what the event viewer is, the different logs it has, and most importantly, how to access it on a Windows 10 computer.

What is the Event Viewer?

Each program you open on your Windows 10 computer sends a notification to a particular activity log in the Event Viewer.

All other activity such as OS changes, security updates, driver quirks, hardware failure, and so on are also posted to a particular log. So you can think of the event viewer as a database that records every activity on your computer.

With the event viewer, you can troubleshoot different Windows and application issues.

If you explore the event viewer in-depth, you will see different information, warnings, and plenty of errors. Don’t freak out – this is normal. Even the best-maintained computers show plenty of errors and warnings.

There are 3 main ways you can gain access to the event viewer on Windows 10 – via the Start menu, Run dialogue, and the command line.

Step 1: Click on Start or press the WIN (Windows) key on your keyboard
Step 2: Search for “Event Viewer”
Step 3: Click on the first search result or press ENTER

ss-1-5

You will be greeted with this page:

ss-2-1

How to Access the Windows 10 Activity Log through the Run Dialogue

Step 1: Right-click on Start (Windows log) and select “Run”, or press WIN (Windows key) + R on your keyboard

ss-3-4

Step 2: Type in “eventvwr” to the editor and click “Ok” or hit ENTER

ss-4-5

ss-5-5

How to Access the Windows 10 Activity Log through the Command Prompt

Step 1: Click on Start (Windows logo) and search for “cmd”
Step 2: Hit Enter or click on the first search result (should be the command prompt) to launch the command prompt

ss-6-3

Step 3: Type in “eventvwr” and hit ENTER

ss-7-2

ss-8-2

Event Viewer Activity Logs

When you open the event viewer to see your computer’s activity logs, you are automatically shown the Event Viewer (Local) tab. But this might not contain the details you need, as it’s just a page you are greeted with when you open the Event Viewer.

There is lots more to the Event Viewer than this.

The Administrative Events Log

You can expand the Custom Views tab to see your computer’s administrative events, like this:

ss-9

The Windows Activity Logs

You can also expand the Windows Logs to show various activities such as:

  • Application Events: Information, errors, and warning reports of program activities

    ss-10

  • Security Events: This shows the results of various security actions. They are called audits and each of them can be a success or a failure

    ss-11

  • Setup Event: this has to do with domain controllers, which is a server that verifies users on computer networks. You shouldn’t worry about them day-to-day.

    ss-12

  • System Events: these are reports from system files detailing the errors they have encountered

    ss-13-1

  • Forwarded Events: these are sent to your computer from other computers in the same network. They help you keep track of the event logs of other computers in the same newtwork.

    ss-14-1

In addition, there are the Application and Service logs, which show hardware and Internet Explorer activities, alongside Microsoft Office apps activities.

You can double click on an error to check its properties, and look up the event ID of the error online. This can help you discover more information on the error so you can fix it if you need to.

ss-15

Conclusion

In this article, you learned about the Windows 10 Event Viewer, which is a very powerful tool Windows users should know how to use.

Apart from viewing various activity logs, it also helps you be aware of what’s happening on your computer.

Thank you for reading. If you consider this article helpful, please share it with your friends and family.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Создание точки восстановления windows server 2019
  • Ovgorskiy windows 10 1903
  • Не работает клавиатура на ноутбуке lenovo windows 10
  • Код активации windows xp professional sp3
  • Virb edit for windows software