- WMI Tasks: Event Logs
- Eventlog Key
- Windows: Логи Выключений/Перезагрузок
- Коды Событий Выключения
- «Просмотр событий» — История Выключений
- Логи Выключений в PowerShell
- О журналах событий About Eventlogs
- Краткое описание Short Description
- Полное описание Long Description
- Просмотр журнала событий Windows PowerShell Viewing the Windows PowerShell Event Log
- Выбор событий для журнала событий Windows PowerShell Selecting Events for the Windows PowerShell Event Log
- События модуля ведения журнала Logging Module Events
- Безопасность и аудит Security and Auditing
- Примечания Notes
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
- 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.
- Open a command prompt window and navigate to the directory where you saved the file.
- Type cscript filename.vbs at the command prompt.
- 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.
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.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
. 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 KeyThe event log contains the following standard logs as well as custom logs:
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.
Each log also contains event sources. For more information, see Event Sources. Windows: Логи Выключений/ПерезагрузокПри диагностики проблемы, которая вызывает неожиданные перезагрузки или выключения машины под управлением Windows, важно знать, какие события могут быть с этим связаны, коды этих событий (англ. event ID) и как найти соответствующие логи. В этой заметке я публикую коды событий, связанных с выключением/перезагрузкой системы. Я также показываю, как просмотреть историю включений/выключений с помощью стандартного приложения «Просмотр событий» (англ. Event Viewer) или из командной строки с помощью PowerShell. Дельный Совет: Загрузка Windows в безопасном режиме! Читать далее → Коды Событий ВыключенияСписок кодов в журнале событий Windows, связанных с выключением или перезагрузкой системы:
«Просмотр событий» — История ВыключенийСобытия связанные с выключениями системы (включая дату и время) могут быть просмотрены с помощью программы «Просмотр событий». Запустить «Просмотр событий» и найти события связанные с выключениями:
Дельный Совет: История команд в PowerShell! Читать далее → Логи Выключений в PowerShellНапример, чтобы отфильтровать 10000 последних записей из системного журнала событий в Windows и отобразить только те события, которые связаны с включениями или выключениями системы, выполните: Дельный Совет: Запуск/Остановка служб в Windows из CMD! Читать далее → О журналах событий About EventlogsКраткое описание Short DescriptionWindows 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.
(Дополнительные сведения о поставщиках Windows PowerShell см. в разделе about_Providers.) (For information about Windows PowerShell providers, see about_Providers.) По умолчанию включены только следующие типы событий: By default, only the following event types are enabled:
Чтобы включить тип событий, задайте для него переменную предпочтение $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. |