The windows event log is full

WMI Tasks: Event Logs

WMI tasks for event logs obtain event data from event log files and perform operations like backing up or clearing log files. For other examples, see the TechNet ScriptCenter at https://www.microsoft.com/technet.

The script examples shown in this topic obtain data only from the local computer. For more information about how to use the script to obtain data from remote computers, see Connecting to WMI on a Remote Computer.

The following procedure describes how to run a script.

To run a script

  1. Copy the code and save it in a file with a .vbs extension, such as filename.vbs. Ensure that your text editor does not add a .txt extension to the file.
  2. Open a command prompt window and navigate to the directory where you saved the file.
  3. Type cscript filename.vbs at the command prompt.
  4. If you cannot access an event log, check to see if you are running from an Elevated command prompt. Some Event Log, such as the Security Event Log, may be protected by User Access Controls (UAC).

By default, cscript displays the output of a script in the command prompt window. Because WMI scripts can produce large amounts of output, you might want to redirect the output to a file. Type cscript filename.vbs > outfile.txt at the command prompt to redirect the output of the filename.vbs script to outfile.txt.

The following table lists script examples that can be used to obtain various types of data from the local computer.

Use the Win32_NTEventlogFile class and the BackupEventLog method. You may need to include the Backup privilege when connecting to WMI. For more information, see Executing Privileged Operations Using VBScript.

How do I. WMI classes or methods
. retrieve information about the Security event log? Include the Security privilege when connecting to the Win32_NTEventlogFile class. For more information, see Executing Privileged Operations Using VBScript.
VB
PowerShell
. back up an event log?
. back up an event log more than once?

Ensure that the backup file has a unique name before using the Win32_NTEventlogFile and the BackupEventLog method. The operating system does not allow you to overwrite an existing backup file; you must either move the backup file or rename it before you can run the script again. You may need to include the Backup privilege when connecting to WMI. For more information, see Executing Privileged Operations Using VBScript.

. determine the number of records in an event log?

Use the Win32_NTEventlogFile class and check the value of the NumberOfRecords property.

Eventlog Key

The event log contains the following standard logs as well as custom logs:

Log Description
Application Contains events logged by applications. For example, a database application might record a file error. The application developer decides which events to record.
Security Contains events such as valid and invalid logon attempts, as well as events related to resource use such as creating, opening, or deleting files or other objects. An administrator can start auditing to record events in the security log.
System Contains events logged by system components, such as the failure of a driver or other system component to load during startup.
CustomLog Contains events logged by applications that create a custom log. Using a custom log enables an application to control the size of the log or attach ACLs for security purposes without affecting other applications.

The event logging service uses the information stored in the Eventlog registry key. The Eventlog key contains several subkeys, called logs. Each log contains information that the event logging service uses to locate resources when an application writes to and reads from the event log.

The structure of the Eventlog key is as follows:

Note that domain controllers record events in the Directory service and File Replication service logs and DNS servers record events in the DNS server.

Each log can contain the following registry values.

Registry value Description
CustomSD Restricts access to the event log. This value is of type REG_SZ. The format used is Security Descriptor Definition Language (SDDL). Construct an ACL that grants one or more of the following rights: Clear (0x0004)
Read (0x0001)
Write (0x0002)
To be a syntactically valid SDDL, the CustomSD value must specify an owner and a group owner (for example, O:BAG:SY), but the owner and group owner are not used. If CustomSD is set to a wrong value, an event is fired in the System event log when the event log service starts, and the event log gets a default security descriptor which is identical to the original CustomSD value for the Application log. SACLs are not supported.
For more information, see Event Logging Security.
Windows Server 2003: SACLs are supported.
Windows XP/2000: This value is not supported.
DisplayNameFile This value is not used. Windows Server 2003 and Windows XP/2000: Name of the file that stores the localized name of the event log. The name stored in this file appears as the log name in Event Viewer. If this entry does not appear in the registry for an event log, Event Viewer displays the name of the registry subkey as the log name. This value is of type REG_EXPAND_SZ. The default value is %SystemRoot%\system32\els.dll.
DisplayNameID This value is not used. Windows Server 2003 and Windows XP/2000: Message identification number of the log name string. This number indicates the message in which the localized display name appears. The message is stored in the file specified by the DisplayNameFile value. This value is of type REG_DWORD.
File Fully qualified path to the file where each event log is stored. This enables Event Viewer and other applications to find the log files. This value is of type REG_SZ or REG_EXPAND_SZ. This value is optional. If the value is not specified, it defaults to %SystemRoot%\system32\winevt\logs\ followed by a file name that is based on the event log registry key name.The specific event log file path should be set using the command line utility wevtutil.exe or by using the EvtSetChannelConfigProperty function with EvtChannelLoggingConfigLogFilePath passed into the PropertyId parameter.
If a specific file is set, make sure that the event log service has full permissions on the file.
This value needs to be a valid file name for a file that is located on a local directory (not a remote computer, not a DOS device, not a floppy, and not a pipe). If the file setting is wrong, an event is fired in the System event log when the event log service starts.
Do not use environment variables, in the path to the file, that cannot be expanded in the context of the event log service.
Windows Server 2003 and Windows XP/2000: This value defaults to %SystemRoot%\system32\config\ followed by a file name that is based on the event log registry key name. If the File setting is set to an invalid value, the log will either not be initialized properly, or all requests will silently go to the default log (Application).
MaxSize Maximum size, in bytes, of the log file. This value is of type REG_DWORD. The value must be set to a multiple of 64K for a System, Application, or Security log. The default value is 1MB.Windows Server 2003 and Windows XP/2000: The value is limited to 0xFFFFFFFF, and the default value is 512K.
PrimaryModule This value is not used.Windows Server 2003 and Windows XP/2000: This value is the name of the subkey that contains the default values for the entries in the subkey for the event source. This value is of type REG_SZ.
Retention This value is of type REG_DWORD. The default value is 0. If this value is 0, the records of events are always overwritten. If this value is 0xFFFFFFFF or any nonzero value, records are never overwritten. When the log file reaches its maximum size, you must clear the log manually; otherwise, new events are discarded. You must also clear the log before you can change its size.Windows Server 2003 and Windows XP/2000: This value is the time interval, in seconds, that records of events are protected from being overwritten. When the age of an event reaches or exceeds this value, it can be overwritten.
Sources This value is not used. Windows Server 2003 and Windows XP/2000: Names of the applications, services, or groups of applications that write events to this log. This value should only be read and not altered. The event log service maintains the list based on each program listed in a subkey under the log. This value is of type REG_MULTI_SZ.
AutoBackupLogFiles This value is of type REG_DWORD, and is used by the event log service to determine whether an event log should be automatically saved. The default value is 0, which disables auto-backup. The service will back up the log file only if the retention value is -1 (0xFFFFFFFF). Other values will be ignored.Windows Server 2003: Retention can be set to -1 (0xFFFFFFFF) or 1 (0x00000001) for AutoBackupLogFiles to work. Other values will be ignored.
RestrictGuestAccess This value is not used. Windows XP/2000: This value is of type REG_DWORD, and the default value is 1. When the value is set to 1, it restricts the Guest and Anonymous account access to the event log, and when this value is 0, it allows Guest account access to the event log.
Isolation Defines the default access permissions for the log. This value is of type REG_SZ. You can specify one of the following values:
  • Application
  • System
  • Custom

The default isolation is Application. The default permissions for Application are (shown using SDDL):
The default permissions for System are (shown using SDDL):
The default permissions for Custom isolation is the same as Application.
Windows Server 2003 and Windows XP/2000: This value is not available.

Each log also contains event sources. For more information, see Event Sources.

Windows: Логи Выключений/Перезагрузок

При диагностики проблемы, которая вызывает неожиданные перезагрузки или выключения машины под управлением Windows, важно знать, какие события могут быть с этим связаны, коды этих событий (англ. event ID) и как найти соответствующие логи.

В этой заметке я публикую коды событий, связанных с выключением/перезагрузкой системы.

Я также показываю, как просмотреть историю включений/выключений с помощью стандартного приложения «Просмотр событий» (англ. Event Viewer) или из командной строки с помощью PowerShell.

Дельный Совет: Загрузка Windows в безопасном режиме! Читать далее →

Коды Событий Выключения

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

Event ID Описание
41 Система была перезагружена без корректного завершения работы.
1074 Система была корректного выключена пользователем или процессом.
1076 Следует за Event ID 6008 и означает, что первый пользователь (с правом выключения системы) подключившийся к серверу после неожиданной перезагрузки или выключения, указал причину этого события.
6005 Запуск «Журнала событий Windows» (англ. Event Log). Указывает на включение системы.
6006 Остановка «Журнала событий Windows» (англ. Event Log). Указывает на выключение системы.
6008 Предыдущее выключение системы было неожиданным.
6009 Версия операционной системы, зафиксированная при загрузке системы.
6013 Время работы системы (англ. system uptime) в секундах.

«Просмотр событий» — История Выключений

События связанные с выключениями системы (включая дату и время) могут быть просмотрены с помощью программы «Просмотр событий».

Запустить «Просмотр событий» и найти события связанные с выключениями:

  1. Нажмите клавишу Win , наберите eventvwr и запустите Просмотр событий
  2. В панели слева разверните Журналы Windows и перейдите в Система
  3. Щелкните правой кнопкой мыши на Система и выберите Фильтр текущего журнала.
  4. Введите следующие коды в поле и нажмите OK :

Дельный Совет: История команд в PowerShell! Читать далее →

Логи Выключений в PowerShell

Например, чтобы отфильтровать 10000 последних записей из системного журнала событий в Windows и отобразить только те события, которые связаны с включениями или выключениями системы, выполните:

Дельный Совет: Запуск/Остановка служб в Windows из CMD! Читать далее →

О журналах событий About Eventlogs

Краткое описание Short Description

Windows PowerShell создает журнал событий Windows с именем «Windows PowerShell» для записи событий Windows PowerShell. Windows PowerShell creates a Windows event log that is named «Windows PowerShell» to record Windows PowerShell events. Этот журнал можно просмотреть в Просмотр событий или с помощью командлетов, получающих события, например Get-EventLog командлет. You can view this log in Event Viewer or by using cmdlets that get events, such as the Get-EventLog cmdlet. По умолчанию обработчики и события поставщика Windows PowerShell записываются в журнал событий, но можно использовать переменные предпочтений журнала событий для настройки журнала событий. By default, Windows PowerShell engine and provider events are recorded in the event log, but you can use the event log preference variables to customize the event log. Например, можно добавить события о командах Windows PowerShell. For example, you can add events about Windows PowerShell commands.

Полное описание Long Description

В журнале событий Windows PowerShell записываются сведения об операциях Windows PowerShell, таких как запуск и остановка ядра программы, а также запуск и остановка поставщиков Windows PowerShell. The Windows PowerShell event log records details of Windows PowerShell operations, such as starting and stopping the program engine and starting and stopping the Windows PowerShell providers. Можно также заносить в журнал сведения о командах Windows PowerShell. You can also log details about Windows PowerShell commands.

Журнал событий Windows PowerShell находится в группе Журналы приложений и служб. The Windows PowerShell event log is in the Application and Services Logs group. Журнал Windows PowerShell — это классический журнал событий, который не использует технологию событий Windows. The Windows PowerShell log is a classic event log that does not use the Windows Eventing technology. Чтобы просмотреть журнал, используйте командлеты, предназначенные для классических журналов событий, например Get-EventLog . To view the log, use the cmdlets designed for classic event logs, such as Get-EventLog .

Просмотр журнала событий Windows PowerShell Viewing the Windows PowerShell Event Log

Журнал событий Windows PowerShell можно просмотреть в Просмотр событий или с помощью Get-EventLog Get-WmiObject командлетов и. You can view the Windows PowerShell event log in Event Viewer or by using the Get-EventLog and Get-WmiObject cmdlets. Чтобы просмотреть содержимое журнала Windows PowerShell, введите: To view the contents of the Windows PowerShell log, type:

Чтобы проверить события и их свойства, используйте Sort-Object командлет, Group-Object командлет и командлеты, которые содержат Format команду ( Format командлеты). To examine the events and their properties, use the Sort-Object cmdlet, the Group-Object cmdlet, and the cmdlets that contain the Format verb (the Format cmdlets).

Например, чтобы просмотреть события в журнале, сгруппированные по ИДЕНТИФИКАТОРу события, введите: For example, to view the events in the log grouped by the event ID, type:

Или введите: Or, type:

Чтобы просмотреть все классические журналы событий, введите: To view all the classic event logs, type:

Кроме того, с помощью Get-WmiObject командлета можно использовать классы инструментарий управления Windows (WMI) (WMI), связанные с событиями, для просмотра журнала событий. You can also use the Get-WmiObject cmdlet to use the event-related Windows Management Instrumentation (WMI) classes to examine the event log. Например, чтобы просмотреть все свойства файла журнала событий, введите: For example, to view all the properties of the event log file, type:

Чтобы найти классы WMI, связанные с событиями Win32, введите: To find the Win32 event-related WMI classes, type:

Для получения дополнительных сведений введите «Get-Help Get-EventLog» и «Get-Help Get-WmiObject». For more information, type «Get-Help Get-EventLog» and «Get-Help Get-WmiObject».

Выбор событий для журнала событий Windows PowerShell Selecting Events for the Windows PowerShell Event Log

Можно использовать переменные предпочтений журнала событий, чтобы определить, какие события записываются в журнал событий Windows PowerShell. You can use the event log preference variables to determine which events are recorded in the Windows PowerShell event log.

Существует шесть переменных предпочтений журнала событий. две переменные для каждого из трех компонентов ведения журнала: ядро (программа Windows PowerShell), поставщики и команды. There are six event log preference variables; two variables for each of the three logging components: the engine (the Windows PowerShell program), the providers, and the commands. Переменные Лифецикливент зарегистрируют нормальные события запуска и остановки. The LifeCycleEvent variables log normal starting and stopping events. Переменные работоспособности регистрируют события ошибок. The Health variables log error events.

В следующей таблице перечислены переменные предпочтений журнала событий. The following table lists the event log preference variables.

Переменная Variable Описание Description
$LogEngineLifeCycleEvent $LogEngineLifeCycleEvent Заносит в журнал начало и конец PowerShell Logs the start and stop of PowerShell
$LogEngineHealthEvent $LogEngineHealthEvent Журналы ошибок программы PowerShell Logs PowerShell program errors
$LogProviderLifeCycleEvent $LogProviderLifeCycleEvent Записывает в журнал начало и конец поставщиков PowerShell Logs the start and stop of PowerShell providers
$LogProviderHealthEvent $LogProviderHealthEvent Регистрирует ошибки поставщика PowerShell Logs PowerShell provider errors
$LogCommandLifeCycleEvent $LogCommandLifeCycleEvent Записывает в журнал запуск и завершение команд Logs the starting and completion of commands
$LogCommandHealthEvent $LogCommandHealthEvent Регистрирует ошибки команды Logs command errors

(Дополнительные сведения о поставщиках Windows PowerShell см. в разделе about_Providers.) (For information about Windows PowerShell providers, see about_Providers.)

По умолчанию включены только следующие типы событий: By default, only the following event types are enabled:

  • $LogEngineLifeCycleEvent $LogEngineLifeCycleEvent
  • $LogEngineHealthEvent $LogEngineHealthEvent
  • $LogProviderLifeCycleEvent $LogProviderLifeCycleEvent
  • $LogProviderHealthEvent $LogProviderHealthEvent

Чтобы включить тип событий, задайте для него переменную предпочтение $true. To enable an event type, set the preference variable for that event type to $true. Например, чтобы включить события жизненного цикла команды, введите: For example, to enable command life-cycle events, type:

Или введите: Or, type:

Чтобы отключить тип события, задайте для него переменную предпочтение $false. To disable an event type, set the preference variable for that event type to $false. Например, чтобы отключить события жизненного цикла команды, введите: For example, to disable command life-cycle events, type:

Можно отключить любое событие, за исключением событий, указывающих на то, что ядро Windows PowerShell и основные поставщики запущены. You can disable any event, except for the events that indicate that the Windows PowerShell engine and the core providers are started. Эти события создаются до запуска профилей Windows PowerShell и перед тем, как программа размещения готова принять команды. These events are generated before the Windows PowerShell profiles are run and before the host program is ready to accept commands.

Параметры переменных применяются только к текущему сеансу Windows PowerShell. The variable settings apply only for the current Windows PowerShell session. Чтобы применить их ко всем сеансам Windows PowerShell, добавьте их в профиль Windows PowerShell. To apply them to all Windows PowerShell sessions, add them to your Windows PowerShell profile.

События модуля ведения журнала Logging Module Events

Начиная с Windows PowerShell 3,0, вы можете записывать события выполнения командлетов и функций в модулях и оснастках Windows PowerShell, установив для свойства LogPipelineExecutionDetails модулей и оснасток значение TRUE. Beginning in Windows PowerShell 3.0, you can record execution events for the cmdlets and functions in Windows PowerShell modules and snap-ins by setting the LogPipelineExecutionDetails property of modules and snap-ins to TRUE. В Windows PowerShell 2,0 эта функция доступна только для оснасток. In Windows PowerShell 2.0, this feature is available only for snap-ins.

Если значение свойства LogPipelineExecutionDetails равно TRUE ( $true ), Windows PowerShell записывает события командлета и выполнения функции в сеансе в журнал Windows PowerShell в Просмотр событий. When the LogPipelineExecutionDetails property value is TRUE ( $true ), Windows PowerShell writes cmdlet and function execution events in the session to the Windows PowerShell log in Event Viewer. Параметр действует только в текущем сеансе. The setting is effective only in the current session.

Чтобы включить ведение журнала событий выполнения командлетов и функций в модуле, используйте следующую последовательность команд. To enable logging of execution events of cmdlets and functions in a module, use the following command sequence.

Чтобы включить ведение журнала событий выполнения командлетов в оснастке, используйте следующую последовательность команд. To enable logging of execution events of cmdlets in a snap-in, use the following command sequence.

Чтобы отключить ведение журнала, используйте ту же последовательность команд, чтобы задать для свойства значение FALSE ( $false ). To disable logging, use the same command sequence to set the property value to FALSE ( $false ).

Можно также использовать параметр групповая политика «включить ведение журнала модуля», чтобы включить и отключить ведение журнала модуля и оснастки. You can also use the «Turn on Module Logging» Group Policy setting to enable and disable module and snap-in logging. Значение политики включает список имен модулей и оснасток. The policy value includes a list of module and snap-in names. Поддерживаются подстановочные знаки. Wildcards are supported.

Если параметр «включить ведение журнала модуля» установлен для модуля, значение свойства LogPipelineExecutionDetails модуля равно TRUE во всех сеансах, и его нельзя изменить. When «Turn on Module Logging» is set for a module, the value of the LogPipelineExecutionDetails property of the module is TRUE in all sessions and it cannot be changed.

Параметр групповой политики включить ведение журнала модуля находится в следующих групповая политика путях: The Turn On Module Logging group policy setting is located in the following Group Policy paths:

Политика конфигурации пользователя имеет приоритет над политикой конфигурации компьютера, и обе политики имеют предпочтение по отношению к значению свойства LogPipelineExecutionDetails модулей и оснасток. The User Configuration policy takes precedence over the Computer Configuration policy, and both policies take preference over the value of the LogPipelineExecutionDetails property of modules and snap-ins.

Дополнительные сведения об этом параметре групповая политика см. в разделе about_Group_Policy_Settings. For more information about this Group Policy setting, see about_Group_Policy_Settings.

Безопасность и аудит Security and Auditing

Журнал событий Windows PowerShell предназначен для указания активности и предоставления оперативных сведений для устранения неполадок. The Windows PowerShell event log is designed to indicate activity and to provide operational details for troubleshooting.

Однако, подобно большинству журналов событий приложений на базе Windows, журнал событий Windows PowerShell не обеспечивает безопасность. However, like most Windows-based application event logs, the Windows PowerShell event log is not designed to be secure. Его не следует использовать для аудита безопасности или записи конфиденциальных или собственных сведений. It should not be used to audit security or to record confidential or proprietary information.

Журналы событий предназначены для чтения и понимания пользователями. Event logs are designed to be read and understood by users. Пользователи могут выполнять чтение и запись в журнал. Users can read from and write to the log. Пользователь-злоумышленник может прочитать журнал событий на локальном или удаленном компьютере, записать ложные данные, а затем предотвратить ведение журнала действий. A malicious user could read an event log on a local or remote computer, record false data, and then prevent the logging of their activities.

Примечания Notes

Авторы модулей могут добавлять функции ведения журнала в свои модули. Authors of module authors can add logging features to their modules. Дополнительные сведения см. в разделе Написание модуля Windows PowerShell. For more information, see Writing a Windows PowerShell Module.

Читайте также:  Windows 10 ускорить утилита
Оцените статью