get eventlog powershell параметры

Работа с журналами в PowerShell

После настройки систем и сервисов, роль админа сводится к наблюдению за их правильной работой и отслеживание текущих параметров. Учитывая, что PS изначально ориентирован на Windows и решения разрабатываемые Microsoft, в его состав входят командлеты позволяющие без сторонней помощи получать нужные данные. Целый ряд командлетов *-Eventlog позволяют легко считать записи в журнале событий как на локальной так и удаленной системе. Просмотреть список всех командлетов с указанием их назначения можно командой:

PS> Get-Help *-Eventlog

get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры
Например, командлет Show-Eventlog запустит консоль «Просмотр событий» на которой будут показаны события локальной системы:

Соответственно, чтобы сразу подключиться к удаленному компьютеру добавляем параметр «-computername имя_системы«.
Наиболее интересный из всего списка командлет — Get-Eventlog, который получает список событий или сами события. Чтобы вывести список всех журналов, вводим:

В результате получим таблицу, в которой будут данные по названию журнала, его текущему и максимальному размеру, и периоду и политики ротации (по мере устаревания, по необходимости).
Смотрим все события безопасности:

get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры
Список будет естественно достаточно большим. Каждому событию будет дано краткое описание. В PS по-умолчанию вывод команды достаточно краток и в него попадают не все данные. Так сделано специально, ведь количество обрабатываемых данных велико. Поэтому чтобы получить действительно необходимую информацию ее нужно запросить специально. Чтобы увидеть полностью все данные по событию, следует использовать командлет Format-List:

PS> Get-Eventlog Security | Format-List

Для краткости параметр «-logname» можно не использовать. В PowerShell данные легко сортируются и отбираются по нужным критериям. Например, чтобы вывести только последние несколько событий на двух компьютерах, используем параметр «Nevest» с указанием требуемого числа:

Теперь выведем только события, имеющие определенный статус:

get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры
Как уже говорилось события можно группировать, выберем 100 последних системных событий и сгрупируем по Id.

И для примера соберем все данные по успешной регистрации пользователей (события с EventID=4624):

PS> Get-Eventlog Security | Where-Object

В PowerShell v.2 появился еще один командлет Get-WinEvent, который в некоторых случаях предоставляет более удобный формат доступа к данным. Получим список провайдеров отвечающие за обновления:

В зависимости от установленных ролей и компонентов список будет разным, но нас интересует провайдер для Windows Update. Теперь смотрим установленные обновления:

В итоге мы можем достаточно просто получить любую информацию по состоянию системы. Учитывая, что количество данных в журналах событий может быть достаточно велико, особенно при сборе информации с нескольких систем, при написании скриптов следует задуматься об оптимизации.

Источник

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.

Источник

Write-Event Log

Writes an event to an event log.

Syntax

Description

The Write-EventLog cmdlet writes an event to an event log.

To write an event to an event log, the event log must exist on the computer and the source must be registered for the event log.

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: Write an event to the Application event log

This command writes an event from the MyApp source to the Application event log.

Example 2: Write an event to the Application event log of a remote computer

This command writes an event from the MyApp source to the Application event log on the Server01 remote computer.

Parameters

Specifies a task category for the event. Enter an integer that is associated with the strings in the category message file for the event log.

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

Specifies a remote 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 of the Get-EventLog cmdlet 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 the entry type of the event. The acceptable values for this parameter are: Error, Warning, Information, SuccessAudit, and FailureAudit. The default value is Information.

For a description of the values, see EventLogEntryType Enumeration.

Type:EventLogEntryType
Aliases:ET
Accepted values:Error, Information, FailureAudit, SuccessAudit, Warning
Position:3
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the event identifier. This parameter is required. The maximum value for the EventId parameter is 65535.

Type:Int32
Aliases:ID, EID
Position:2
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the name of the log to which the event is written. Enter the log name. The log name is the value of the Log property, not the LogDisplayName. Wildcard characters are not permitted. This parameter is required.

Type:String
Aliases:LN
Position:0
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the event message. This parameter is required.

Type:String
Aliases:MSG
Position:4
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the binary data that is associated with the event, in bytes.

Type:Byte [ ]
Aliases:RD
Position:Named
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Specifies the event source, which is typically the name of the application that is writing the event to the log.

Type:String
Aliases:SRC
Position:1
Default value:None
Accept pipeline input:False
Accept wildcard characters:False

Inputs

None

You cannot pipe input to this cmdlet.

Outputs

This cmdlet returns objects that represents the events in the logs.

Notes

For some Windows event logs, writing events requires administrator rights. You must start PowerShell using the Run as Administrator option.

Источник

about_Eventlogs

Short Description

Windows PowerShell creates a Windows event log that is named «Windows PowerShell» to record Windows PowerShell events. You can view this log in Event Viewer or by using cmdlets that get events, such as the Get-EventLog cmdlet. 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. For example, you can add events about Windows PowerShell commands.

Long Description

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. You can also log details about Windows PowerShell commands.

Viewing the Windows PowerShell Event Log

You can view the Windows PowerShell event log in Event Viewer or by using the Get-EventLog and Get-WmiObject cmdlets. To view the contents of the Windows PowerShell log, type:

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:

To view all the classic event logs, type:

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:

To find the Win32 event-related WMI classes, type:

For more information, type «Get-Help Get-EventLog» and «Get-Help Get-WmiObject».

Selecting Events for the Windows PowerShell Event Log

You can use the event log preference variables to determine which events are recorded in the Windows PowerShell event log.

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.

VariableDescription
$LogEngineLifeCycleEventLogs the start and stop of PowerShell
$LogEngineHealthEventLogs PowerShell program errors
$LogProviderLifeCycleEventLogs the start and stop of PowerShell providers
$LogProviderHealthEventLogs PowerShell provider errors
$LogCommandLifeCycleEventLogs the starting and completion of commands
$LogCommandHealthEventLogs command errors

(For information about Windows PowerShell providers, see about_Providers.)

By default, only the following event types are enabled:

You can disable any event, except for the events that indicate that the Windows PowerShell engine and the core providers are started. These events are generated before the Windows PowerShell profiles are run and before the host program is ready to accept commands.

The variable settings apply only for the current Windows PowerShell session. To apply them to all Windows PowerShell sessions, add them to your Windows PowerShell profile.

Logging Module Events

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. In Windows PowerShell 2.0, this feature is available only for snap-ins.

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.

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.

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:

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.

For more information about this Group Policy setting, see about_Group_Policy_Settings.

Security and Auditing

The Windows PowerShell event log is designed to indicate activity and to provide operational details for troubleshooting.

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. For more information, see Writing a Windows PowerShell Module.

Источник

Блог системного администратора Windows/Linux/FreeBSD

get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры

Просмотр логов Windows на удаленном компьютере с помощью Powershell

Для просмотра логов Windows можно использовать команды Get-WinEvent и Get-EventLog

Get-EventLog получает список журналов или событий в заданном журнале на локальном или удалённом компьютере. Указывая нужные параметры для Get-EventLog, можно с лёгкостью искать искомые события по значениям их свойств. Get-EventLog возвращает события, соответствующие всем указанным значениям свойств. Командлет Get-EventLog работает только со стандартными классическими журналами событий Windows. Если нужно искать по остальным событиям из журналов Windows, используйте командлет Get-WinEvent.

Представим, что вам нужна основная информация о журналах событий на вашем компьютере. В этом случае убедитесь, что вы включили параметр list при вызове Get-EventLog:

Если вам нужна только информация о конкретном журнале событий, используйте командлет Where-Object, чтобы ограничить извлечение данных конкретным журналом событий:

Эта команда извлекает все события в журнале событий системы:

Вот данные, которые вы получите:
get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры

Чтобы получить более подробную информацию, просто добавьте командлет Format-List:

Полученная информация будет уже такой:
get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры

Вы также можете передавать данные через командлет Where-Object для возврата подмножества событий. Например, эта команда извлекает только те события в журнале событий Windows PowerShell, у которых значение EventID равно 403:

get eventlog powershell параметры. Смотреть фото get eventlog powershell параметры. Смотреть картинку get eventlog powershell параметры. Картинка про get eventlog powershell параметры. Фото get eventlog powershell параметры

Вот небольшая команда, которая извлекает все события в журнале событий Windows PowerShell, а затем использует командлет Group-Object для группировки этих событий с помощью EventID. Другими словами, команда подсчитывает общее количество событий для каждого идентификатора (например, произошло два события с EventID 300, произошло шесть событий с событием EventID 400 и т. Д.). Затем эти данные передаются через командлет Sort-Object для предоставления результатов, отсортированных по EventID. Вот команда:

Примеры использования Get-Eventlog:

Поиск событий по ID после 3 июля:

Поиск в логах нескольких серверов:

Возвращает все события журнала Windows PowerShell, в сообщениях которых содержится слово «failed»:

Поиск событий, статус которых «Ошибка»:

Примеры использования Get-Winevent:

Поиск в логе System по ID 6005:

Поиск событий за последние 40 дней:

Поиск событий за последние 5 дней для Outlook:

Поиск в логах нескольких серверов:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *