- Show-Event Log
- Syntax
- Description
- Examples
- Example 1: Display event logs for the local computer
- Example 2: Display event logs for a remote computer
- Parameters
- Inputs
- Outputs
- Notes
- Сведения о ведении журнала About Logging
- Краткое описание Short description
- Подробное описание Long description
- Просмотр записей журнала событий PowerShell в Windows Viewing the PowerShell event log entries 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
- Get-Event Log
- Syntax
- Description
- Examples
- Example 1: Get event logs on the local computer
- Example 2: Get recent entries from an event log on the local computer
- Example 3: Find all sources for a specific number of entries in an event log
- Example 4: Get error events from a specific event log
- Example 5: Get events from an event log with an InstanceId and Source value
- Example 6: Get events from multiple computers
- Example 7: Get all events that include a specific word in the message
- Example 8: Display the property values of an event
- Example 9: Get events from an event log using a source and event ID
- Example 10: Get events and group by a property
- Example 11: Get events that occurred during a specific date and time range
- Parameters
- Inputs
- Outputs
- Notes
Show-Event Log
Displays the event logs of the local or a remote computer in Event Viewer.
Syntax
Description
The Show-EventLog cmdlet opens Event Viewer on the local computer and displays in it all of the classic event logs on the local computer or a remote computer.
To open Event Viewer on Windows Vista and later versions of the Windows operating system, the current user must be a member of the Administrators group on the local computer.
The cmdlets that contain the EventLog noun (the EventLog cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of the Windows operating system, use the Get-WinEvent cmdlet.
Examples
Example 1: Display event logs for the local computer
This command opens Event Viewer and displays in it the classic event logs on the local computer.
Example 2: Display event logs for a remote computer
This command opens Event Viewer and displays in it the classic event logs on the Server01 computer.
Parameters
Specifies a remote computer. Show-EventLog displays the event logs from the specified computer in Event Viewer on the local computer. The default is the local computer.
Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer.
This parameter does not rely on Windows PowerShell remoting. You can use the ComputerName parameter even if your computer is not configured to run remote commands.
Type: | String |
Aliases: | CN |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
None
You cannot pipe input to this cmdlet.
Outputs
None
This cmdlet does not generate any output.
Notes
The Windows PowerShell command prompt returns as soon as Event Viewer opens. You can work in the current session while Event Viewer is open.
Because this cmdlet requires a user interface, it does not work on Server Core installations of Windows Server.
Сведения о ведении журнала About Logging
Краткое описание Short description
PowerShell регистрирует внутренние операции из подсистемы, поставщиков и командлетов. PowerShell logs internal operations from the engine, providers, and cmdlets.
Подробное описание 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. Журнал событий находится в группе Журналы приложений и служб и называется Microsoft-Windows-PowerShell . The event log is located in the Application and Services Logs group and is named Microsoft-Windows-PowerShell . Связанным поставщиком ETW GUID является
Если включено ведение журнала блокировки сценариев, PowerShell регистрирует в журнале следующие события Microsoft-Windows-PowerShell/Operational : When Script Block Logging is enabled, PowerShell logs the following events to the Microsoft-Windows-PowerShell/Operational log:
Поле Field | Значение Value |
---|---|
EventId EventId | 4104 / 0x1008 |
Канал Channel | Operational |
Level Level | Verbose |
Код операции Opcode | Create |
Задача Task | CommandStart |
Ключевое слово Keyword | Runspace |
Включение ведения журнала блоков сценариев 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:
Get-Event Log
Gets the events in an event log, or a list of the event logs, on the local computer or remote computers.
Syntax
Description
The Get-EventLog cmdlet gets events and event logs from local and remote computers. By default, Get-EventLog gets logs from the local computer. To get logs from remote computers, use the ComputerName parameter.
You can use the Get-EventLog parameters and property values to search for events. The cmdlet gets events that match the specified property values.
PowerShell cmdlets that contain the EventLog noun work only on Windows classic event logs such as Application, System, or Security. To get logs that use the Windows Event Log technology in Windows Vista and later Windows versions, use Get-WinEvent .
Get-EventLog uses a Win32 API that is deprecated. The results may not be accurate. Use the Get-WinEvent cmdlet instead.
Examples
Example 1: Get event logs on the local computer
This example displays the list of event logs that are available on the local computer. The names in the Log column are used with the LogName parameter to specify which log is searched for events.
The Get-EventLog cmdlet uses the List parameter to display the available logs.
Example 2: Get recent entries from an event log on the local computer
This example gets recent entries from the System event log.
The Get-EventLog cmdlet uses the LogName parameter to specify the System event log. The Newest parameter returns the five most recent events.
Example 3: Find all sources for a specific number of entries in an event log
This example shows how to find all of the sources that are included in the 1000 most recent entries in the System event log.
The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The Newest parameter selects the 1000 most recent events. The event objects are stored in the $Events variable. The $Events objects are sent down the pipeline to the Group-Object cmdlet. Group-Object uses the Property parameter to group the objects by source and counts the number of objects for each source. The NoElement parameter removes the group members from the output. The Sort-Object cmdlet uses the Property parameter to sort by the count of each source name. The Descending parameter sorts the list in order by count from highest to lowest.
Example 4: Get error events from a specific event log
This example gets error events from the System event log.
The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The EntryType parameter filters the events to show only Error events.
Example 5: Get events from an event log with an InstanceId and Source value
This example gets events from the System log for a specific InstanceId and Source.
The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The InstanceID parameter selects the events with the specified Instance ID. The Source parameter specifies the event property.
Example 6: Get events from multiple computers
This command gets the events from the System event log on three computers: Server01, Server02, and Server03.
The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The ComputerName parameter uses a comma-separated string to list the computers from which you want to get the event logs.
Example 7: Get all events that include a specific word in the message
This command gets all the events in the System event log that contain a specific word in the event’s message. It’s possible that your specified Message parameter’s value is included in the message’s content but isn’t displayed on the PowerShell console.
The Get-EventLog cmdlet uses the LogName parameter to specify the System event log. The Message parameter specifies a word to search for in the message field of each event.
Example 8: Display the property values of an event
This example shows how to display all of an event’s properties and values.
The Get-EventLog cmdlet uses the LogName parameter to specify the System event log. The Newest parameter selects the most recent event object. The object is stored in the $A variable. The object in the $A variable is sent down the pipeline to the Select-Object cmdlet. Select-Object uses the Property parameter with an asterisk ( * ) to select all of the object’s properties.
Example 9: Get events from an event log using a source and event ID
This example gets events for a specified Source and Event ID.
The Get-EventLog cmdlet uses the LogName parameter to specify the Application event log. The Source parameter specifies the application name, Outlook. The objects are sent down the pipeline to the Where-Object cmdlet. For each object in the pipeline, the Where-Object cmdlet uses the variable $_.EventID to compare the Event ID property to the specified value. The objects are sent down the pipeline to the Select-Object cmdlet. Select-Object uses the Property parameter to select the properties to display in the PowerShell console.
Example 10: Get events and group by a property
The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The UserName parameter includes the asterisk ( * ) wildcard to specify a portion of the user name. The event objects are sent down the pipeline to the Group-Object cmdlet. Group-Object uses the Property parameter to specify that the UserName property is used to group the objects and count the number of objects for each user name. The NoElement parameter removes the group members from the output. The objects are sent down the pipeline to the Select-Object cmdlet. Select-Object uses the Property parameter to select the properties to display in the PowerShell console.
Example 11: Get events that occurred during a specific date and time range
This example gets Error events from the System event log for a specified date and time range. The Before and After parameters set the date and time range but are excluded from the output.
The Get-Date cmdlet uses the Date parameter to specify a date and time. The DateTime objects are stored in the $Begin and $End variables. The Get-EventLog cmdlet uses the LogName parameter to specify the System log. The EntryType parameter specifies the Error event type. The date and time range is set by the After parameter and $Begin variable and the Before parameter and $End variable.
Parameters
Gets events that occurred after a specified date and time. The After parameter date and time are excluded from the output. Enter a DateTime object, such as the value returned by the Get-Date cmdlet.
Type: | DateTime |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that this cmdlet returns a standard System.Diagnostics.EventLogEntry object for each event. Without this parameter, Get-EventLog returns an extended PSObject object with additional EventLogName, Source, and InstanceId properties.
To see the effect of this parameter, pipe the events to the Get-Member cmdlet and examine the TypeName value in the result.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that this cmdlet returns the output as strings, instead of objects.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Gets events that occurred before a specified date and time. The Before parameter date and time are excluded from the output. Enter a DateTime object, such as the value returned by the Get-Date cmdlet.
Type: | DateTime |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter specifies a remote computer’s NetBIOS name, Internet Protocol (IP) address, or a fully qualified domain name (FQDN).
If the ComputerName parameter isn’t specified, Get-EventLog defaults to the local computer. The parameter also accepts a dot ( . ) to specify the local computer.
The ComputerName parameter doesn’t rely on Windows PowerShell remoting. You can use Get-EventLog with the ComputerName parameter even if your computer is not configured to run remote commands.
Type: | String [ ] |
Aliases: | Cn |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, the entry type of the events that this cmdlet gets.
The acceptable values for this parameter are:
- Error
- Information
- FailureAudit
- SuccessAudit
- Warning
Type: | String [ ] |
Aliases: | ET |
Accepted values: | Error, Information, FailureAudit, SuccessAudit, Warning |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the index values to get from the event log. The parameter accepts a comma-separated string of values.
Type: | Int32 [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the Instance IDs to get from the event log. The parameter accepts a comma-separated string of values.
Type: | Int64 [ ] |
Position: | 1 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Displays the list of event logs on the computer.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the name of one event log. To find the log names use Get-EventLog -List . Wildcard characters are permitted. This parameter is required.
Type: | String |
Aliases: | LN |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies a string in the event message. You can use this parameter to search for messages that contain certain words or phrases. Wildcards are permitted.
Type: | String |
Aliases: | MSG |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Begins with the newest events and gets the specified number of events. The number of events is required, for example -Newest 100 . Specifies the maximum number of events that are returned.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies, as a string array, sources that were written to the log that this cmdlet gets. Wildcards are permitted.
Type: | String [ ] |
Aliases: | ABO |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Specifies, as a string array, user names that are associated with events. Enter names or name patterns, such as User01 , User* , or Domain01\User* . Wildcards are permitted.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | True |
Inputs
None
You cannot pipe input to Get-EventLog .
Outputs
System.Diagnostics.EventLogEntry. System.Diagnostics.EventLog. System.String
If the LogName parameter is specified, the output is a collection of System.Diagnostics.EventLogEntry objects.
If only the List parameter is specified, the output is a collection of System.Diagnostics.EventLog objects.
If both the List and AsString parameters are specified, the output is a collection of System.String objects.
Notes
The cmdlets Get-EventLog and Get-WinEvent are not supported in the Windows Preinstallation Environment (Windows PE).