- О журналах событий 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
- Сведения о окнах ведения журнала About Logging Windows
- Краткое описание Short description
- Подробное описание Long description
- Просмотр записей журнала событий PowerShell в Windows Viewing the PowerShell event log entries on Windows
- Регистрация поставщика событий PowerShell в Windows Registering the PowerShell event provider on Windows
- Отмена регистрации поставщика событий PowerShell в Windows Unregistering the PowerShell event provider on Windows
- Включение ведения журнала блоков сценариев Enabling Script Block Logging
- Использование групповой политики Using Group Policy
- Использование реестра Using the Registry
- Ведение журнала защищенных событий Protected Event Logging
- Включение ведения журнала защищенных событий с помощью групповая политика Enabling Protected Event Logging via Group Policy
- Расшифровка сообщений журнала защищенных событий Decrypting Protected Event Logging messages
О журналах событий 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.
Сведения о окнах ведения журнала About Logging Windows
Краткое описание Short description
PowerShell регистрирует внутренние операции из подсистемы, поставщиков и командлетов в журнале событий Windows. PowerShell logs internal operations from the engine, providers, and cmdlets to the Windows event log.
Подробное описание Long description
PowerShell регистрирует сведения об операциях PowerShell, таких как запуск и остановка подсистемы и поставщиков, а также выполнение команд PowerShell. PowerShell logs details about PowerShell operations, such as starting and stopping the engine and providers, and executing PowerShell commands.
В Windows PowerShell версии 3,0, 4,0, 5,0 и 5,1 включены командлеты EventLog для журналов событий Windows. Windows PowerShell versions 3.0, 4.0, 5.0, and 5.1 include EventLog cmdlets for the Windows event logs. В этих версиях для вывода списка типов командлетов EventLog : Get-Command -Noun EventLog . In those versions, to display the list of EventLog cmdlets type: Get-Command -Noun EventLog . Дополнительные сведения см. в документации по командлетам и about_EventLogs для вашей версии Windows PowerShell. For more information, see the cmdlet documentation and about_EventLogs for your version of Windows PowerShell.
Просмотр записей журнала событий PowerShell в Windows Viewing the PowerShell event log entries on Windows
Журналы PowerShell можно просмотреть с помощью Просмотр событий Windows. PowerShell logs can be viewed using the Windows Event Viewer. Журнал событий находится в группе Журналы приложений и служб и называется PowerShellCore . The event log is located in the Application and Services Logs group and is named PowerShellCore . Связанным поставщиком ETW GUID является
Если включено ведение журнала блокировки сценариев, PowerShell регистрирует в журнале следующие события PowerShellCore/Operational : When Script Block Logging is enabled, PowerShell logs the following events to the PowerShellCore/Operational log:
Поле Field | Значение Value |
---|---|
EventId EventId | 4104 / 0x1008 |
Channel Channel | Operational |
Level Level | Verbose |
Код операции Opcode | Create |
Задача Task | CommandStart |
Ключевое слово Keyword | Runspace |
Регистрация поставщика событий PowerShell в Windows Registering the PowerShell event provider on Windows
В отличие от Linux или macOS, Windows требует регистрации поставщика событий, прежде чем события могут быть записаны в журнал событий. Unlike Linux or macOS, Windows requires the event provider to be registered before events can be written to the event log. Чтобы включить поставщик событий PowerShell, выполните следующую команду в командной строке PowerShell с повышенными привилегиями. To enable the PowerShell event provider, run the following command from an elevated PowerShell prompt.
Отмена регистрации поставщика событий PowerShell в Windows Unregistering the PowerShell event provider on Windows
Регистрация поставщика событий помещает блокировку в двоичную библиотеку, используемую для расшифровки событий. Registering the event provider places a lock in the binary library used to decode events. Чтобы обновить эту библиотеку, необходимо отменить регистрацию поставщика, чтобы освободить эту блокировку. To update this library, the provider must be unregistered to release this lock.
Чтобы отменить регистрацию поставщика PowerShell, выполните следующую команду в командной строке PowerShell с повышенными привилегиями. To unregister the PowerShell provider, run the following command from an elevated PowerShell prompt.
После обновления PowerShell выполните команду, $PSHOME\RegisterManifest.ps1 чтобы зарегистрировать обновленный поставщик событий. After updating PowerShell, run $PSHOME\RegisterManifest.ps1 to register the updated event provider.
Включение ведения журнала блоков сценариев Enabling Script Block Logging
При включении ведения журнала блока сценариев PowerShell записывает содержимое всех блоков сценариев, которые он обрабатывает. When you enable Script Block Logging, PowerShell records the content of all script blocks that it processes. После включения все новые сеансы PowerShell регистрируют эти сведения. Once enabled, any new PowerShell session logs this information.
Рекомендуется включить ведение журнала защищенных событий, как описано ниже, при использовании журнала блокировки сценариев для любых операций, кроме целей диагностики. It’s recommended to enable Protected Event Logging, as described below, when using Script Block Logging for anything other than diagnostics purposes.
Ведение журнала блока скрипта можно включить с помощью групповая политика или параметра реестра. Script Block Logging can be enabled via Group Policy or a registry setting.
Использование групповой политики Using Group Policy
Чтобы включить автоматическую транскрипцию, включите эту Turn on PowerShell Script Block Logging функцию в групповая политика с помощью Administrative Templates -> Windows Components -> Windows PowerShell . To enable automatic transcription, enable the Turn on PowerShell Script Block Logging feature in Group Policy through Administrative Templates -> Windows Components -> Windows PowerShell .
Использование реестра Using the Registry
Выполните следующую функцию: Run the following function:
Ведение журнала защищенных событий Protected Event Logging
Увеличение уровня ведения журналов в системе повышает вероятность того, что содержимое журнала может содержать конфиденциальные данные. Increasing the level of logging on a system increases the possibility that logged content may contain sensitive data. Например, если включено ведение журнала сценариев, то учетные данные или другие конфиденциальные данные, используемые сценарием, могут быть записаны в журнал событий. For example, with script logging enabled, credentials or other sensitive data used by a script can be written to the event log. При компрометации компьютера, на котором зарегистрированы конфиденциальные данные, журналы могут предоставить злоумышленнику информацию, необходимую для расширения их доступности. When a machine that has logged sensitive data is compromised, the logs can provide an attacker with information needed to extend their reach.
Для защиты этих сведений в Windows 10 появился журнал защищенных событий. To protect this information, Windows 10 introduces Protected Event Logging. Защищенное ведение журнала событий позволяет участвующим приложениям шифровать конфиденциальные данные, записанные в журнал событий. Protected Event Logging lets participating applications encrypt sensitive data written to the event log. Позже вы сможете расшифровать и обработать эти журналы на более безопасном и централизованном сборщике журналов. Later, you can decrypt and process these logs on a more secure and centralized log collector.
Содержимое журнала событий защищено с помощью стандартного синтаксиса сообщений (CMS) IETF. Event log content is protected using the IETF Cryptographic Message Syntax (CMS) standard. CMS использует шифрование с открытым ключом. CMS uses public key cryptography. Ключи, используемые для шифрования содержимого и расшифровки содержимого, хранятся отдельно. The keys used to encrypt content and decrypt content are kept separate.
Открытый ключ может быть общим и не конфиденциальным. The public key can be shared widely and isn’t sensitive data. Любое содержимое, зашифрованное с помощью этого открытого ключа, может быть расшифровано только закрытым ключом. Any content encrypted with this public key can only be decrypted by the private key. Дополнительные сведения о шифровании с открытым ключом см. в статье о шифровании с открытым ключом Википедии. For more information about Public Key Cryptography, see Wikipedia — Public Key Cryptography.
Чтобы включить политику защищенного ведения журнала событий, разверните открытый ключ для всех компьютеров, которые содержат данные журнала событий для защиты. To enable a Protected Event Logging policy, deploy a public key to all machines that have event log data to protect. Соответствующий закрытый ключ используется для последующей обработки журналов событий в более безопасном расположении, например в центральном сборщике журналов событий или SIEM агрегаторе. The corresponding private key is used to post-process the event logs at a more secure location such as a central event log collector, or SIEM aggregator. Вы можете настроить SIEM в Azure. You can set up SIEM in Azure. Дополнительные сведения см. в разделе Универсальная интеграция SIEM. For more information, see Generic SIEM integration.
Включение ведения журнала защищенных событий с помощью групповая политика Enabling Protected Event Logging via Group Policy
Чтобы включить ведение журнала защищенных событий, включите Enable Protected Event Logging функцию в групповая политика с помощью Administrative Templates -> Windows Components -> Event Logging . To enable Protected Event Logging, enable the Enable Protected Event Logging feature in Group Policy through Administrative Templates -> Windows Components -> Event Logging . Для этого параметра требуется сертификат шифрования, который можно указать в одной из следующих форм: This setting requires an encryption certificate, which you can provide in one of several forms:
- Содержимое сертификата X. 509 в кодировке Base-64 (например, предложено Export параметром в диспетчере сертификатов). The content of a base-64 encoded X.509 certificate (for example, as offered by the Export option in Certificate Manager).
- Отпечаток сертификата, который можно найти в хранилище сертификатов локального компьютера (может быть развернут инфраструктурой PKI). The thumbprint of a certificate that can be found in the Local Machine certificate store (can be deployed by PKI infrastructure).
- Полный путь к сертификату (может быть локальным или удаленным общим ресурсом). The full path to a certificate (can be local, or a remote share).
- Путь к каталогу, содержащему сертификат или сертификаты (может быть локальным или удаленным общим ресурсом). The path to a directory containing a certificate or certificates (can be local, or a remote share).
- Имя субъекта сертификата, который можно найти в хранилище сертификатов локального компьютера (может быть развернуто инфраструктурой PKI). The subject name of a certificate that can be found in the Local Machine certificate store (can be deployed by PKI infrastructure).
Итоговый сертификат должен иметь Document Encryption в качестве расширенного использования ключа ( 1.3.6.1.4.1.311.80.1 ), а Data Encipherment также значение или Key Encipherment Использование ключей. The resulting certificate must have Document Encryption as an enhanced key usage ( 1.3.6.1.4.1.311.80.1 ), and either Data Encipherment or Key Encipherment key usages enabled.
Закрытый ключ не должен быть развернут на компьютерах, регистрируемых в журнале событий. The private key shouldn’t be deployed to the machines logging events. Он должен храниться в безопасном месте, где вы расшифровываете сообщения. It should be kept in a secure location where you decrypt the messages.
Расшифровка сообщений журнала защищенных событий Decrypting Protected Event Logging messages
Следующий сценарий будет получен и расшифрован, предполагая, что у вас есть закрытый ключ: The following script will retrieve and decrypt, assuming that you have the private key: