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

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.

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! Читать далее →

Get-Win Event

Gets events from event logs and event tracing log files on local and remote computers.

Syntax

Description

The Get-WinEvent cmdlet gets events from event logs, including classic logs, such as the System and Application logs. The cmdlet gets data from event logs that are generated by the Windows Event Log technology introduced in Windows Vista. And, events in log files generated by Event Tracing for Windows (ETW). By default, Get-WinEvent returns event information in the order of newest to oldest.

Get-WinEvent lists event logs and event log providers. To interrupt the command, press CTRL + C . You can get events from selected logs or from logs generated by selected event providers. And, you can combine events from multiple sources in a single command. Get-WinEvent allows you to filter events using XPath queries, structured XML queries, and hash table queries.

If you’re not running PowerShell as an Administrator, you might see error messages that you cannot retrieve information about a log.

Examples

Example 1: Get all the logs from a local computer

This command gets all the event logs on the local computer. Logs are listed in the order that Get-WinEvent gets them. Classic logs are retrieved first, followed by the new Windows Event logs. It’s possible for a log’s RecordCount to be null, which is blank, or zero.

Читайте также:  Linux get pid parent

The Get-WinEvent cmdlet gets log information from the computer. The ListLog parameter uses the asterisk ( * ) wildcard to display information about each log.

Example 2: Get the classic Setup log

This command gets an EventLogConfiguration object that represents the classic Setup log. The object includes information about the log, such as file size, provider, file path, and whether the log is enabled.

The Get-WinEvent cmdlet uses the ListLog parameter to specify the Setup log. The object is sent down the pipeline to the Format-List cmdlet. Format-List uses the Property parameter with the asterisk ( * ) wildcard to display each property.

Example 3: Get event logs from a server

This command only gets event logs on the local computer that contain events. It’s possible for a log’s RecordCount to be null or zero. The example uses the $_ variable. For more information, see about_Automatic_Variables.

The Get-WinEvent cmdlet gets log information from the computer. The ListLog parameter uses the asterisk ( * ) wildcard to display information about each log. The ComputerName parameter specifies to get the logs from the local computer, localhost. The objects are sent down the pipeline to the Where-Object cmdlet. Where-Object uses $_.RecordCount to return only logs that contain data. $_ is a variable that represents the current object in the pipeline. RecordCount is a property of the object with a non-null value.

Example 4: Get event logs from multiple servers

This example gets objects that represent the Application event logs on three computers: Server01, Server02, and Server03. The ForEach keyword is used because the ComputerName parameter accepts only one value. For more information, see about_Foreach.

The variable $S stores the names three servers: Server01, Server02, and Server03. The ForEach statement uses a loop to process each server, ($Server in $S) . The script block in the curly braces ( < >) runs the Get-WinEvent command. The ListLog parameter specifies the Application log. The ComputerName parameter uses the variable $Server to get log information from each server.

The objects are sent down the pipeline to the Select-Object cmdlet. Select-Object gets the properties LogMode, MaximumSizeInBytes, RecordCount, LogName, and uses a calculated expression to display the ComputerName using the $Server variable. The objects are sent down the pipeline to the Format-Table cmdlet to display the output in the PowerShell console. The AutoSize parameter formats the output to fit the screen.

Example 5: Get event log providers and log names

This command gets the event log providers and the logs to which they write.

The Get-WinEvent cmdlet gets log information from the computer. The ListProvider parameter uses the asterisk ( * ) wildcard to display information about each provider. In the output, the Name is the provider and LogLinks is the log that the provider writes to.

Example 6: Get all event log providers that write to a specific log

This command gets all of the providers that write to the Application log.

The Get-WinEvent cmdlet gets log information from the computer. The ListLog parameter uses Application to get objects for that log. ProviderNames is a property of the object and displays the providers that write to the Application log.

Example 7: Get event log provider names that contain a specific string

This command gets the event log providers with names that include a specific string in the provider’s name.

The Get-WinEvent cmdlet gets log information from the computer. The ListProvider parameter uses the asterisk ( * ) wildcard to find Policy anywhere within the provider’s name.

Example 8: Get Event Ids that the event provider generates

This command lists the Event Ids that the Microsoft-Windows-GroupPolicy event provider generates along with the event description.

The Get-WinEvent cmdlet gets log information from the computer. The ListProvider parameter specifies the provider, Microsoft-Windows-GroupPolicy. The expression is wrapped in parentheses and uses the Events property to get objects. The objects are sent down the pipeline to the Format-Table cmdlet. Format-Table displays the Id and Description of the event objects.

Example 9: Get log information from event object properties

This example shows how to get information about a log’s contents using event object properties. Event objects are stored in a variable and then grouped and counted by Event Id and Level.

The Get-WinEvent cmdlet uses the LogName parameter to specify the Windows PowerShell event log. The event objects are stored in the $Event variable. The Count property of $Event shows the total number of logged events.

The $Event variable is sent down the pipeline to the Group-Object cmdlet. Group-Object uses the Property parameter to specify the Id property and counts the objects by the event Id value. The NoElement parameter removes other properties from the objects output. The grouped objects are sent down the pipeline to the Sort-Object cmdlet. Sort-Object uses the Property parameter to sort the objects by Count. The Descending parameter displays the output by count, from highest to lowest. In the output, the Count column contains the total number of each event. The Name column contains the grouped event Id numbers.

The $Event variable is sent down the pipeline to the Group-Object cmdlet. Group-Object uses the Property parameter to specify the LevelDisplayName property and counts the objects by LevelDisplayName. The objects are grouped by the levels such as Warning and Information. The NoElement parameter removes other properties from the output. In the output, the Count column contains the total number of each event. The Name column contains the grouped LevelDisplayName.

Example 10: Get error events that have a specified string in their name

This example uses a comma-separated string of log names. The output is grouped by the level such as error or warning and the log name.

The Get-WinEvent cmdlet gets log information from the computer. The LogName parameter uses a comma-separated string with the asterisk ( * ) wildcard to specify the log names. The objects are sent down the pipeline to the Group-Object cmdlet. Group-Object uses the Property parameter to group the objects by LevelDisplayName and LogName. The NoElement parameter removes other properties from the output. The grouped objects are sent down the pipeline to the Format-Table cmdlet. Format-Table uses the AutoSize parameter to format the columns. The Count column contains the total number of each event. The Name column contains the grouped LevelDisplayName and LogName.

Читайте также:  Драйвера для ноутбука asus eee pc windows

Example 11: Get events from an archived event log

Get-WinEvent can get event information from saved log files. This sample uses an archived PowerShell log that is stored on the local computer.

The Get-WinEvent cmdlet gets log information from the computer. The Path parameter specifies the directory and file name.

Example 12: Get a specific number of events from an archived event log

These commands get a specific number of events from an archived event log. Get-WinEvent has parameters that can get a maximum number of events or the oldest events. This sample uses an archived PowerShell log that is stored in C:\Test\PowerShellCore Operational.evtx.

The Get-WinEvent cmdlet gets log information from the computer. The Path parameter specifies the directory and filename. The MaxEvents parameter specifies that 100 records are displayed, from newest to oldest.

Example 13: Event Tracing for Windows

Event Tracing for Windows (ETW) writes events to the log as events occur. The events are stored in the order of oldest to newest. An archived ETW file is saved as an .etl such as TraceLog.etl. The events are listed in the order in which they are written to the log, so the Oldest parameter is required.

The Get-WinEvent cmdlet gets log information from the archived file. The Path parameter specifies the directory and file name. The Oldest parameter is used to output events in the order they are written, oldest to newest. The objects are sent down the pipeline to the Sort-Object cmdlet Sort-Object sorts the objects in descending order by the value of the TimeCreated property. The objects are sent down the pipeline to the Select-Object cmdlet that displays the 100 newest events.

Example 14: Get events from an event trace log

This example shows how to get the events from an event trace log file ( .etl ) and an archived Windows PowerShell log file ( .evtx ). You can combine multiple file types in a single command. Because the files contain the same type of .NET Framework object, EventLogRecord, you can filter them with the same properties. The command requires the Oldest parameter because it is reading from an .etl file, but the Oldest parameter applies to each file.

The Get-WinEvent cmdlet gets log information from the archived files. The Path parameter uses a comma-separated list to specify each files directory and file name. The Oldest parameter is used to output events in the order they are written, oldest to newest. The objects are sent down the pipeline to the Where-Object cmdlet. Where-Object uses a script block to find events with and Id of 403. The $_ variable represents the current object in the pipeline and Id is the Event Id property.

Example 15: Filter event log results

This example shows a variety of methods to filter and select events from an event log. All of these commands get events that occurred in the last 24-hours from the Windows PowerShell event log. The filter methods are more efficient than using the Where-Object cmdlet. Filters are applied as the objects are retrieved. Where-Object retrieves all of the objects, then applies filters to all of the objects.

Example 16: Use FilterHashtable to get events from the Application log

This example uses the FilterHashtable parameter to get events from the Application log. The hash table uses key/value pairs. For more information about the FilterHashtable parameter, see Creating Get-WinEvent queries with FilterHashtable. For more information about hash tables, see about_Hash_Tables.

The Get-Date cmdlet uses the AddDays method to get a date that is two days before the current date. The date object is stored in the $Date variable.

The Get-WinEvent cmdlet gets log information. The FilterHashtable parameter is used to filter the output. The LogName key specifies the value as the Application log. The StartTime key uses the value stored in the $Date variable. The Id key uses an Event Id value, 1003.

Example 17: Use FilterHashtable to get application errors

This example uses the FilterHashtable parameter to find Internet Explorer application errors that occurred within the last week.

The Get-Date cmdlet uses the AddDays method to get a date that is seven days before the current date. The date object is stored in the $StartTime variable.

The Get-WinEvent cmdlet gets log information. The FilterHashtable parameter is used to filter the output. The LogName key specifies the value as the Application log. The ProviderName key uses the value, Application Error, which is the event’s Source. The Data key uses the value iexplore.exe The StartTime key uses the value stored in $StartTime variable.

Parameters

Specifies the name of the computer that this cmdlet gets events from the event logs. Type the NetBIOS name, an IP address, or the fully qualified domain name (FQDN) of the computer. The default value is the local computer, localhost. This parameter accepts only one computer name at a time.

To get event logs from remote computers, configure the firewall port for the event log service to allow remote access.

This cmdlet does not rely on PowerShell remoting. You can use the ComputerName parameter even if your computer is not configured to run remote commands.

Type: String
Aliases: Cn
Position: Named
Default value: Local computer
Accept pipeline input: False
Accept wildcard characters: False

Specifies a user account that has permission to perform this action. The default value is the current user.

Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, you are prompted for a password. If you type only the parameter name, you are prompted for both a username and a password.

Type: PSCredential
Position: Named
Default value: Current user
Accept pipeline input: False
Accept wildcard characters: False

Specifies a query in hash table format to select events from one or more event logs. The query contains a hash table with one or more key/value pairs.

Читайте также:  Астра линукс как восстановить удаленный файл

Hash table queries have the following rules:

  • Keys and values are case-insensitive.
  • Wildcard characters are valid only in the values associated with the LogName and ProviderName keys.
  • Each key can be listed only once in each hash table.
  • The Path value takes paths to .etl , .evt , and .evtx log files.
  • The LogName, Path, and ProviderName keys can be used in the same query.
  • The UserID key can take a valid security identifier (SID) or a domain account name that can be used to construct a valid System.Security.Principal.NTAccount object.
  • The Data value takes event data in an unnamed field. For example, events in classic event logs.

When Get-WinEvent cannot interpret a key/value pair, it interprets the key as a case-sensitive name for the event data in the event.

The valid Get-WinEvent key/value pairs are as follows:

  • LogName=
  • ProviderName=
  • Path=
  • Keywords=
  • ID=
  • Level=
  • StartTime=
  • EndTime=
  • UserID=
  • Data=
Type: Hashtable [ ]
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies a structured XML query that this cmdlet selects events from one or more event logs.

To generate a valid XML query, use the Create Custom View and Filter Current Log features in Windows Event Viewer. Use the items in the dialog box to create a query, and then click the XML tab to view the query in XML format. You can copy the XML from the XML tab into the value of the FilterXml parameter. For more information about the Event Viewer features, see Event Viewer Help.

Use an XML query to create a complex query that contains several XPath statements. The XML format also allows you to use a Suppress XML element that excludes events from the query. For more information about the XML schema for event log queries, see Query Schema and the XML Event Queries section of Event Selection.

Type: XmlDocument
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies an XPath query that this cmdlet select events from one or more logs.

For more information about the XPath language, see XPath Reference and the Selection Filters section of Event Selection.

Type: String
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Gets debug and analytic logs, in addition to other event logs. The Force parameter is required to get a debug or analytic log when the value of the name parameter includes wildcard characters.

By default, the Get-WinEvent cmdlet excludes these logs unless you specify the full name of a debug or analytic log.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies the event logs. Enter the event log names in a comma-separated list. Wildcards are permitted. To get all the logs, use the asterisk ( * ) wildcard.

Type: String [ ]
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: True

Specifies the event log providers that this cmdlet gets. An event log provider is a program or service that writes events to the event log.

Enter the provider names in a comma-separated list. Wildcards are permitted. To get the providers of all the event logs on the computer, use the asterisk ( * ) wildcard.

Type: String [ ]
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: True

Specifies the event logs that this cmdlet get events from. Enter the event log names in a comma-separated list. Wildcards are permitted. You can also pipe log names to the Get-WinEvent cmdlet.

PowerShell does not limit the amount of logs you can request. However, the Get-WinEvent cmdlet queries the Windows API which has a limit of 256. This can make it difficult to filter through all of your logs at one time. You can work around this by using a foreach loop to iterate through each log like this: Get-WinEvent -ListLog * | ForEach-Object

Type: String [ ]
Position: 1
Default value: None
Accept pipeline input: True
Accept wildcard characters: True

Specifies the maximum number of events that are returned. Enter an integer such as 100. The default is to return all the events in the logs or files.

Type: Int64
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Indicate that this cmdlet gets the events in oldest-first order. By default, events are returned in newest-first order.

This parameter is required to get events from .etl and .evt files and from debug and analytic logs. In these files, events are recorded in oldest-first order, and the events can be returned only in oldest-first order.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies the path to the event log files that this cmdlet get events from. Enter the paths to the log files in a comma-separated list, or use wildcard characters to create file path patterns.

Get-WinEvent supports files with the .evt , .evtx , and .etl file name extensions. You can include events from different files and file types in the same command.

Type: String [ ]
Aliases: PSPath
Position: 1
Default value: None
Accept pipeline input: True
Accept wildcard characters: True

Specifies, as a string array, the event log providers from which this cmdlet gets events. Enter the provider names in a comma-separated list, or use wildcard characters to create provider name patterns.

An event log provider is a program or service that writes events to the event log. It is not a PowerShell provider.

Type: String [ ]
Position: 1
Default value: None
Accept pipeline input: True
Accept wildcard characters: True

Inputs

System.String, System.Xml.XmlDocument, System.Collections.Hashtable

You can pipeline a LogName (string), a FilterXML query, or a FilterHashtable query to Get-WinEvent .

Outputs

System.Diagnostics.Eventing.Reader.EventLogConfiguration, System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diagnostics.Eventing.Reader.ProviderMetadata

With the ListLog parameter, Get-WinEvent returns System.Diagnostics.Eventing.Reader.EventLogConfiguration objects.

With the ListProvider parameter, Get-WinEvent returns System.Diagnostics.Eventing.Reader.ProviderMetadata objects.

With all other parameters, Get-WinEvent returns System.Diagnostics.Eventing.Reader.EventLogRecord objects.

Notes

Get-WinEvent is designed to replace the Get-EventLog cmdlet on computers running Windows Vista and later versions of Windows. Get-EventLog gets events only in classic event logs. Get-EventLog is retained for backward compatibility.

The Get-WinEvent and Get-EventLog cmdlets are not supported in Windows Pre-installation Environment (Windows PE).

Оцените статью