- Event Log. Source Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- 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
Event Log. Source Свойство
Определение
Возвращает или задает имя источника, регистрируемого в журнале и используемого при записи в журнал событий. Gets or sets the source name to register and use when writing to the event log.
Значение свойства
Имя, регистрируемое в журнале событий как имя источника записей. The name registered with the event log as a source of entries. Значение по умолчанию — пустая строка («»). The default is an empty string («»).
Исключения
При таком имени источника длина пути к разделу реестра превышает 254 символа. The source name results in a registry key path longer than 254 characters.
Примеры
В следующем примере создается источник MySource , если он еще не существует, и записывается запись в журнал событий MyNewLog . The following example creates the source MySource if it does not already exist, and writes an entry to the event log MyNewLog .
Комментарии
Источник события указывает, в каком журнале регистрируется событие. The event source indicates what logs the event. Часто это имя приложения или имя подкомпонента приложения, если приложение велико. It is often the name of the application, or the name of a subcomponent of the application, if the application is large. Приложения и службы должны записывать в журнал приложений или пользовательский журнал. Applications and services should write to the Application log or a custom log. Драйверы устройств должны записывать в системный журнал. Device drivers should write to the System log.
При записи в журнал событий необходимо указывать только источник событий. You only need to specify an event source if you are writing to an event log. Перед записью записи в журнал событий необходимо зарегистрировать источник событий в журнале событий в качестве допустимого источника событий. Before writing an entry to an event log, you must register the event source with the event log as a valid source of events. При написании записи журнала система использует Source свойство для поиска соответствующего журнала, в котором будет размещена запись. When you write a log entry, the system uses the Source property to find the appropriate log in which to place your entry. При чтении журнала событий можно указать либо Source , либо Log и MachineName . If you are reading the event log, you can either specify the Source, or a Log and MachineName.
При MachineName подключении к журналу на локальном компьютере указывать параметр не требуется. You are not required to specify the MachineName if you are connecting to a log on the local computer. Если не указать MachineName , предполагается, что используется локальный компьютер («.»). If you do not specify the MachineName, the local computer («.») is assumed.
Используйте WriteEvent и WriteEntry для записи событий в журнал событий. Use WriteEvent and WriteEntry to write events to an event log. Для записи событий необходимо указать источник события. перед записью первой записи с источником необходимо создать и настроить источник события. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.
Создайте новый источник событий во время установки приложения. Create the new event source during the installation of your application. Это позволяет операционной системе обновлять свой список зарегистрированных источников событий и их конфигурацию. This allows time for the operating system to refresh its list of registered event sources and their configuration. Если операционная система не обновила список источников событий и вы пытаетесь написать событие с новым источником, операция записи завершится ошибкой. If the operating system has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail. Новый источник можно настроить с помощью EventLogInstaller или с помощью CreateEventSource метода. You can configure a new source using an EventLogInstaller, or using the CreateEventSource method. Для создания нового источника событий необходимо иметь права администратора на компьютере. You must have administrative rights on the computer to create a new event source.
Можно создать источник событий для существующего журнала событий или нового журнала событий. You can create an event source for an existing event log or a new event log. При создании нового источника для нового журнала событий система регистрирует источник для этого журнала, но журнал не создается, пока в него не будет записана первая запись. When you create a new source for a new event log, the system registers the source for that log, but the log is not created until the first entry is written to it.
Источник должен быть уникальным на локальном компьютере; новое имя источника не может совпадать с существующим именем источника или именем существующего журнала событий. The source must be unique on the local computer; a new source name cannot match an existing source name or an existing event log name. Каждый источник может записывать только один журнал событий; Однако приложение может использовать несколько источников для записи в несколько журналов событий. Each source can write to only one event log at a time; however, your application can use multiple sources to write to multiple event logs. Например, приложению может потребоваться несколько источников, настроенных для различных журналов событий или разных файлов ресурсов. For example, your application might require multiple sources configured for different event logs or different resource files.
При изменении Source значения EventLog закрывается объект, в который он зарегистрирован, и освобождаются все дескрипторы событий. If you change the Source value, the EventLog to which it is registered is closed and all event handles are released.
Источник должен быть настроен либо для записи локализованных записей, либо для записи прямых строк. The source must be configured either for writing localized entries or for writing direct strings. Если приложение записывает записи, используя как идентификаторы ресурсов, так и строковые значения, необходимо зарегистрировать два отдельных источника. If your application writes entries using both resource identifiers and string values, you must register two separate sources. Например, можно настроить один источник с файлами ресурсов, а затем использовать этот источник в WriteEvent методе для записи записей, использующих идентификаторы ресурсов, в журнал событий. For example, configure one source with resource files, and then use that source in the WriteEvent method to write entries using resource identifiers to the event log. Затем создайте другой источник без файлов ресурсов и используйте этот источник в WriteEntry методе для записи строк непосредственно в журнал событий с помощью этого источника. Then create a different source without resource files, and use that source in the WriteEntry method to write strings directly to the event log using that source.
Чтобы изменить сведения о конфигурации существующего источника, необходимо удалить источник, а затем создать его с новой конфигурацией. To change the configuration details of an existing source, you must delete the source and then create it with the new configuration. Если другие приложения или компоненты используют существующий источник, создайте новый источник с обновленной конфигурацией, а не удалите существующий источник. If other applications or components use the existing source, create a new source with the updated configuration rather than deleting the existing source.
Если источник уже сопоставлен с журналом и вы переменяете его в новый журнал, необходимо перезагрузить компьютер, чтобы изменения вступили в силу. If a source has already been mapped to a log and you remap it to a new log, you must restart the computer for the changes to take effect.
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).