Event logs form the core of most monitoring and
diagnosis on Windows. To support this activity, PowerShell offers both the
Get-EventLog
and
Get-WinEvent
cmdlets to let you query and
work with event log data on a system. In addition to simple event log
retrieval, PowerShell also includes many other cmdlets to create, delete,
customize, and interact with event logs.
In addition to the (now “classic”) event logs
exposed by the *-EventLog
cmdlets, Windows Vista and
beyond have a significantly expanded and revamped event logging system
compared to Windows XP. The features of the new system are different
enough that we expose them through an entirely new
Get-WinEvent
cmdlet. If you need to read events from
Vista-style event logs, you’ll need the Get-WinEvent
cmdlet. If you need to read events from classic event logs, the choice is
up to you.
To list all classic event logs on a system,
use the -List
parameter of the
Get-EventLog
cmdlet:
PS > Get-EventLog -List Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 20,480 0 OverwriteAsNeeded 1,933 Application 15,168 0 OverwriteAsNeeded 0 DFS Replication 20,480 0 OverwriteAsNeeded 0 HardwareEvents 512 7 OverwriteOlder 0 Internet Explorer 20,480 0 OverwriteAsNeeded 0 Key Management Service 8,192 0 OverwriteAsNeeded 0 Media Center 128 0 OverwriteAsNeeded 2 OAlerts 1,024 7 OverwriteOlder 424 ScriptEvents 20,480 0 OverwriteAsNeeded 39,006 Security 20,480 0 OverwriteAsNeeded 55,958 System 15,360 0 OverwriteAsNeeded 2,865 Windows PowerShell
On Windows Vista or later, you can also use
the Get-WinEvent
cmdlet. In addition to classic event
logs, the Get-WinEvent
cmdlet supports Application
and Services event logs:
PS > Get-WinEvent -ListLog * | Select LogName,RecordCount LogName RecordCount ------- ----------- Application 1933 DFS Replication 0 HardwareEvents 0 Internet Explorer 0 Key Management Service 0 Media Center 0 OAlerts 2 ScriptEvents 424 Security 39005 System 55957 Windows PowerShell 2865 ForwardedEvents Microsoft-Windows-Backup 0 Microsoft-Windows-Bits-Client/Ana ... Microsoft-Windows-Bits-Client/Oper... 2232 Microsoft-Windows-Bluetooth-MTPEnu... 0 Microsoft-Windows-CAPI2/Operational (...)
To browse event logs using the Windows Event
Viewer graphical user interface, use the Show-EventLog
cmdlet.
The -List
parameter of the Get-EventLog
cmdlet
generates a list of the event logs registered on the system. In addition
to supporting event logs on the current system, all of PowerShell’s
event log cmdlets let you supply the -ComputerName
parameter to interact with event logs on a remote system.
Once you’ve determined which event log you are
interested in, you can use the Get-EventLog
and
Get-WinEvent
cmdlets to search, filter, and retrieve
specific entries from those logs. For information on how to retrieve
event log entries, see Recipes , , and .
For more information about the Get-EventLog
cmdlet, type Get-Help Get-EventLog
. For more information
about the Get-WinEvent
cmdlet, type
Get-Help Get-WinEvent
.
To retrieve the most recent entries from an
event log, use the -Newest
parameter
of the Get-EventLog
cmdlet, as shown
in Example 23-1.
Example 23-1. Retrieving the 10 newest entries from the System event log
PS > Get-EventLog System -Newest 10 | Format-Table Index,Source,Message -Auto Index Source Message ----- ------ ------- 2922 Service Control Manager The Background Intelligent Transfer Servi... 2921 Service Control Manager The Background Intelligent Transfer Servi... 2920 Service Control Manager The Logical Disk Manager Administrative S... 2919 Service Control Manager The Logical Disk Manager Administrative S... 2918 Service Control Manager The Logical Disk Manager Administrative S... 2917 TermServDevices Driver Microsoft XPS Document Writer requ... 2916 Print Printer Microsoft Office Document Image W... 2915 Print Printer Microsoft Office Document Image W... 2914 Print Printer Microsoft Office Document Image W... 2913 TermServDevices Driver Microsoft Shared Fax Driver requir...
Alternatively, use the
-MaxEvents
parameter of the
Get-WinEvent
cmdlet:
PS > Get-WinEvent Application -MaxEvents 10 | Format-Table ProviderName,Id,Message -Auto ProviderName Id Message ------------ -- ------- VSS 8224 The VSS service is shutting down due to ... System Restore 8194 Successfully created restore point (Proc... System Restore 8194 Successfully created restore point (Proc... VSS 8224 The VSS service is shutting down due to ... System Restore 8211 Successfully created scheduled restore p... System Restore 8194 Successfully created restore point (Proc... Microsoft-Windows-MSDTC 2 4202 MSDTC started with the following setting... VSS 8224 The VSS service is shutting down due to ... System Restore 8211 Successfully created scheduled restore p... System Restore 8194 Successfully created restore point (Proc...
The -Newest
parameter of the Get-EventLog
cmdlet
retrieves the most recent entries from an event log that you specify. To
list the event logs available on the system, see List All Event Logs. The Get-WinEvent
cmdlet returns the most recent entries by default, so no specific
parameter is required.
For more information about the Get-EventLog
cmdlet, type Get-Help Get-EventLog
.
To find specific event log entries, use the
Get-EventLog
or Get-WinEvent
cmdlet to retrieve the
items, and then pipe them to the Where-Object
cmdlet to
filter them, as shown in Example 23-2.
Example 23-2. Searching the event log for entries that mention the term “disk”
PS > Get-EventLog System | Where-Object { $_.Message -match "disk" } Index Time Type Source EventID Message ----- ---- ---- ------ ------- ------- 2920 May 06 09:18 Info Service Control M... 7036 The Logical Disk... 2919 May 06 09:17 Info Service Control M... 7036 The Logical Disk... 2918 May 06 09:17 Info Service Control M... 7035 The Logical Disk... 2884 May 06 00:28 Erro sr 1 The System Resto... 2333 Apr 03 00:16 Erro Disk 11 The driver detec... 2332 Apr 03 00:16 Erro Disk 11 The driver detec... 2131 Mar 27 13:59 Info Service Control M... 7036 The Logical Disk... 2127 Mar 27 12:48 Info Service Control M... 7036 The Logical Disk... 2126 Mar 27 12:48 Info Service Control M... 7035 The Logical Disk... 2123 Mar 27 12:31 Info Service Control M... 7036 The Logical Disk... 2122 Mar 27 12:29 Info Service Control M... 7036 The Logical Disk... 2121 Mar 27 12:29 Info Service Control M... 7035 The Logical Disk...
Since the Get-EventLog
cmdlet retrieves rich objects
that represent event log entries, you can pipe them to the Where-Object
cmdlet for equally rich
filtering.
By default, PowerShell’s default table
formatting displays a summary of event log entries. If you are searching
the event log message, however, you are probably interested in seeing
more details about the message itself. In this case, use the Format-List
cmdlet to format these entries in
a more detailed list view. Example 23-3 shows this
view.
Example 23-3. A detailed list view of an event log entry
PS > Get-EventLog System | Where-Object { $_.Message -match "disk" } | Format-List Index : 2920 EntryType : Information EventID : 7036 Message : The Logical Disk Manager Administrative Service service entered the stopped state. Category : (0) CategoryNumber : 0 ReplacementStrings : {Logical Disk Manager Administrative Service, stopped } Source : Service Control Manager TimeGenerated : 5/6/2007 9:18:25 AM TimeWritten : 5/6/2007 9:18:25 AM UserName : Index : 2919 (...)
For more information about the Get-EventLog
cmdlet, type Get-Help Get-EventLog
. For more information
about filtering command output, see Filter Items in a List or Command Output.
To retrieve a specific event log entry, use
the Get-EventLog
cmdlet to retrieve
the entries in the event log, and then pipe them to the Where-Object
cmdlet to filter them to the one
you are looking for.
PS > Get-EventLog System | Where-Object { $_.Index -eq 2920 } Index Time Type Source EventID Message ----- ---- ---- ------ ------- ------- 2920 May 06 09:18 Info Service Control M... 7036 The Logical Disk...
For more advanced (or performance-sensitive)
queries, use the -FilterXml
,
-FilterHashtable
, or -FilterXPath
parameters of the Get-WinEvent
cmdlet:
Get-WinEvent -LogName "System" -FilterXPath "*[System[EventRecordID = 2920]]"
If you’ve listed the items in an event log or searched it for entries that have a message with specific text, you often want to get more details about a specific event log entry.
Since the Get-EventLog
cmdlet retrieves rich objects
that represent event log entries, you can pipe them to the Where-Object
cmdlet for equally rich
filtering.
By default, PowerShell’s default table
formatting displays a summary of event log entries. If you are
retrieving a specific entry, however, you are probably interested in
seeing more details about the entry. In this case, use the Format-List
cmdlet to format these entries in
a more detailed list view, as shown in Example 23-4.
Example 23-4. A detailed list view of an event log entry
PS > Get-EventLog System | Where-Object { $_.Index -eq 2920 } | Format-List Index : 2920 EntryType : Information EventID : 7036 Message : The Logical Disk Manager Administrative Service service entered the stopped state. Category : (0) CategoryNumber : 0 ReplacementStrings : {Logical Disk Manager Administrative Service, stopped } Source : Service Control Manager TimeGenerated : 5/6/2007 9:18:25 AM TimeWritten : 5/6/2007 9:18:25 AM UserName : Index : 2919 (...)
While the Where-Object
cmdlet works well for simple (or one-off) tasks, the
Get
-WinEvent
cmdlet offers three parameters that can make your event log searches
both more powerful and more efficient.
If you have a simple event log query, you
can use the -FilterHashtable
parameter of the
Get-WinEvent
cmdlet to filter the event log very
efficiently.
The -FilterHashtable
parameter works only on Windows 7. On Windows Vista, it generates
an error: “The parameter is incorrect.”
The hashtable that you supply to this parameter lets you
filter on LogName
, ProviderName
,
Path
, Keywords
,
ID
, Level
,
StartTime
, EndTime
, and
UserID
. This can replace many
Where-Object
style filtering operations. This
example retrieves all critical and error events in the System event
log:
Get-WinEvent -FilterHashtable @{ LogName = "System"; Level = 1,2 }
When you are reviewing an event log, the
Windows Event Viewer offers a Filter Current Log action on the
righthand side. This interface lets you select data ranges, event
severity, keywords, task categories, and more. After customizing a
filter, you can click the XML tab to see an XML representation of your
query. You can copy and paste that XML directly into a here string in
a script, and then pass it to the -FilterXml
parameter of the Get-WinEvent
cmdlet:
## Gets all Critical and Error events from the last 24 hours $xml = @' <QueryList> <Query Id="0" Path="System"> <Select Path="System"> *[System[(Level=1 or Level=2) and TimeCreated[timediff(@SystemTime) <= 86400000]]] </Select> </Query> </QueryList> '@ Get-WinEvent -FilterXml $xml
Under the covers, event logs store their
event information in an XML format. In addition to the
-FilterHashtable
and -FilterXml
parameters, the Get-WinEvent
cmdlet lets you filter
event logs with a subset of the standard XPath XML querying language.
XPath lets your filters describe complex hierarchical queries, value
ranges, and more.
Like regular expressions, the XPath query language is by no means simple or easy to understand. This parameter can help if you already have some degree of knowledge or comfort in XPath, but don’t let it intimidate or frustrate you. There is always more than one way to do it.
While the XPath querying language is powerful, the type of
rules you can express ultimately depend on what is contained in the
XML of the actual events. To see what can be contained in the XML of
an event, search MSDN for “windows ‘event schema’”. The online
reference is useful, but actual events tend to contain an extremely
small subset of the supported XML nodes. Because of that, you might
have more success reviewing the XML of events that interest you and
forming XPath queries based on those. Here are some example queries
that build on the -FilterXPath
parameter:
## Search by Event ID Get-WinEvent -LogName "System" -FilterXPath "*[System[(EventID=1)]]" ## Search for events associated with a given Process ID Get-WinEvent -LogName "System" -FilterXPath "*[System/Execution[@ProcessID=428]]" ## Search for events that have 'Volume Shadow Copy' as one of the replacement strings Get-WinEvent -LogName "System" -FilterXPath "*[EventData[Data = 'Volume Shadow Copy']]" ## Search for Windows Installer Events associated with Vista SP1 $query = "*[UserData/CbsPackageInitiateChanges[PackageIdentifier = 'KB936330']]" Get-WinEvent -LogName "System" -FilterXPath $query
To find event log entries by frequency, use
the Get-EventLog
cmdlet to retrieve
the entries in the event log, and then pipe them to the Group-Object
cmdlet to
group them by their message.
PS > Get-EventLog System | Group-Object Message | Sort-Object -Desc Count Count Name Group ----- ---- ----- 23 The Background Intelli... {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 23 The Background Intelli... {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 3 The Logical Disk Manag... {LEE-DESK, LEE-DESK, LEE-DESK} 3 The Logical Disk Manag... {LEE-DESK, LEE-DESK, LEE-DESK} 3 The Logical Disk Manag... {LEE-DESK, LEE-DESK, LEE-DESK} 161 Driver Microsoft XPS D... {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... (...)
The Group-Object
cmdlet is a useful way to
determine which events occur most frequently on your system. It also
provides a useful way to summarize the information in the event
log.
If you want more information about the items
in a specific group, use the Where-Object
cmdlet. Since we used the
Message
property in the Group-Object
cmdlet, we need to filter on
Message
in the Where-Object
cmdlet. For example, to learn
more about the entries relating to the Microsoft XPS Driver (from the
scenario in the solution):
PS > Get-EventLog System | Where-Object { $_.Message -like "Driver Microsoft XPS*" } Index Time Type Source EventID Message ----- ---- ---- ------ ------- ------- 2917 May 06 09:13 Erro TermServDevices 1111 Driver Microsoft... 2883 May 05 10:40 Erro TermServDevices 1111 Driver Microsoft... 2877 May 05 08:10 Erro TermServDevices 1111 Driver Microsoft... (...)
If grouping by message doesn’t provide useful information, you can group by any other property—such as source:
PS > Get-EventLog Application | Group-Object Source Count Name Group ----- ---- ----- 4 Application {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK} 191 Media Center Scheduler {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 1082 MSSQL$SQLEXPRESS {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... (...)
If you’ve listed the items in an event log or searched it for entries that have a message with specific text, you often want to get more details about a specific event log entry.
By default, PowerShell’s default table
formatting displays a summary of event log entries. If you are
retrieving a specific entry, however, you are probably interested in
seeing more details about the entry. In this case, use the Format-List
cmdlet to
format these entries in a more detailed list view, as shown in Example 23-5.
Example 23-5. A detailed list view of an event log entry
PS > Get-EventLog System | Where-Object { $_.Index -eq 2917 } | Format-List Index : 2917 EntryType : Error EventID : 1111 Message : Driver Microsoft XPS Document Writer required for printer Microsoft XPS Document Writer is unknown. Contact the administrator to install the driver before you log in again. Category : (0) CategoryNumber : 0 ReplacementStrings : {Microsoft XPS Document Writer, Microsoft XPS Document Writer} Source : TermServDevices TimeGenerated : 5/6/2007 9:13:31 AM TimeWritten : 5/6/2007 9:13:31 AM UserName :
For more information about the Get-EventLog
cmdlet, type Get-Help Get-EventLog
. For more information
about filtering command output, see Filter Items in a List or Command Output. For more
information about the Group-Object
cmdlet, type Get-Help Group-Object
.
To store event log entries in a file, use the wevtutil.exe application:
PS > wevtutil epl System c: empsystem.bak.evtx
After exporting the event log, use the
Get-WinEvent
cmdlet to query the
exported log as though it were live:
PS > Get-WinEvent -FilterHashtable @{ LogName="System"; Level=1,2 } -MaxEvents 2 | Format-Table -Auto TimeCreated ProviderName Id Message ----------- ------------ -- ------- 2/15/2010 11:49:31 AM Ntfs 55 The file system structure on the disk is ... 2/15/2010 11:49:31 AM Ntfs 55 The file system structure on the disk is ... PS > Get-WinEvent -FilterHashtable @{ Path="c: empsystem.bak.evtx"; Level=1,2 } -MaxEvents 2 | Format-Table -Auto TimeCreated ProviderName Id Message ----------- ------------ -- ------- 2/15/2010 11:49:31 AM Ntfs 55 The file system structure on the disk is ... 2/15/2010 11:49:31 AM Ntfs 55 The file system structure on the disk is ...
If you need to process the event logs on a
system where the Get-WinEvent
cmdlet is not
available, use the Get-EventLog
cmdlet to retrieve the entries in the event log, and then pipe them to
the Export-CliXml
cmdlet to
store them in a file.
Get-EventLog System | Export-CliXml c: empSystemLogBackup.clixml
While there is no PowerShell cmdlet to export
event logs, the wevtutil.exe application provides
an easy way to save an event log to disk in its full fidelity. After
exporting the event log, you can import it again, or even use the
Get-WinEvent
cmdlet to query against it
directly.
If you want to analyze the event logs on a
machine where the Get-WinEvent
cmdlet is not
available, you can use the Export-CliXml
cmdlet to
save event logs to disk—just as PowerShell lets you save any other
structured data to disk. Once you’ve exported the events from an event
log, you can archive them, or use the Import-CliXml
cmdlet to
review them on any machine that has PowerShell installed:
PS > $archivedLogs = Import-CliXml c: empSystemLogBackup.clixml PS > $archivedLogs | Group Source Count Name Group ----- ---- ----- 856 Service Control Manager {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 640 TermServDevices {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 91 Print {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 100 WMPNetworkSvc {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 123 Tcpip {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... (...)
In addition to the
Export-CliXml
cmdlet, you can also use WMI’s
Win32_NTEventLogFile
class to back up classic event
logs:
$log = Get-WmiObject Win32_NTEventLogFile -Filter "LogFileName = 'Application'" $log.BackupEventlog("c: empapplication_backup.log")
After saving a log, you can use the Open Saved Log feature in the Windows Event Viewer to review it.
For more information about the Get-EventLog
cmdlet, type Get-Help Get-EventLog
. For more information
about the Export-CliXml
and Import-CliXml
cmdlets, type Get-Help Export-CliXml
and Get-Help Import-CliXml
,
respectively.
Use the New-EventLog
and Remove-EventLog
cmdlets to create and
remove event logs:
PS > New-EventLog -Logname ScriptEvents -Source PowerShellCookbook PS > Get-EventLog -List Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 20,480 0 OverwriteAsNeeded 1,930 Application (...) 512 7 OverwriteOlder 0 ScriptEvents (...) 15,360 0 OverwriteAsNeeded 2,847 Windows PowerShell PS > Remove-EventLog ScriptEvents
Both cmdlets support remote administration via
the -ComputerName
parameter.
Although Windows offers the standard
Application
event log, you might sometimes want to
make separate event logs to hold events of special interest. For this,
PowerShell includes the New-EventLog
cmdlet. It takes
two parameters: the event log name and the source identifier for events.
If the event log does not already exist, PowerShell creates it. If both
the event log and event log source already exist, the
New-EventLog
cmdlet generates an error.
After you create the event log, the
Limit-EventLog
cmdlet lets you manage its retention
policy. For more information about the Limit-EventLog
cmdlet, see Clear or Maintain an Event Log.
The Remove-EventLog
cmdlet
lets you remove both event logs and event log sources.
Be careful when deleting event logs, as it is difficult to recreate all the event sources if you delete the wrong log by accident. If you delete a standard event log, you have little hope for recovery.
To remove just an event log source, use the
-Source
parameter:
Remove-EventLog -Source PowerShellCookbook
To
remove an event log altogether, specify the log name in the
-Logname
parameter:
Remove-EventLog -LogName ScriptEvents
Once you have created an event log, you can
use the Write-EventLog
cmdlet to work with it. For
more information about writing to event logs, see Write to an Event Log.
Use the Write-EventLog
cmdlet to write events
to an event log:
PS > Write-EventLog -LogName ScriptEvents -Source PowerShellCookbook ` -EventId 1234 -Message "Hello World" PS > Get-EventLog ScriptEvents | Select EntryType,Source,InstanceId,Message EntryType Source InstanceId Message --------- ------ ---------- ------- Information PowerShellCookbook 1234 Hello World
The Write-EventLog
cmdlet
lets you write event log messages to a specified event log. To write an
event log message, you must supply a valid log name and a registered
event log source. If you need to create a new event log or register a
new event source, see Create or Remove an Event Log.
In addition to the log name and source, the
Write-EventLog
cmdlet also requires an event ID and
message. Within an event log and event source, each event ID should
uniquely identify the situation being logged: for example,
logon failure or disk full.
This makes it easy for scripts and other management tasks to
automatically respond to system events. The event message should
elaborate on the situation being logged (for example, the username or
drive letter), but should not be required to identify its reason.
Use the schtasks.exe tool to define a new task that reacts to event log entries. As its action, call powershell.exe with the arguments to disable the profile, customize the execution policy, hide its window, and launch a script:
$cred = Get-Credential $password = $cred.GetNetworkCredential().Password ## Define the command that task scheduler should run when the event ## occurs $command = "PowerShell -NoProfile -ExecutionPolicy RemoteSigned " + "-WindowStyle Hidden -File 'C:Program FilesTaskScriptsScriptEvents.ps1'" ## Create a new scheduled task SCHTASKS /Create /TN "ScriptEvents Monitor" /TR $command /SC ONEVENT ` /RL Highest /RU $cred.Username /RP $password ` /EC ScriptEvents /MO *[System/EventID=1010]
In Vista and beyond, the Windows event log lets you define custom actions that launch when an event is generated. Although you can use the user interface to create these tasks and filters, the schtasks.exe tool lets you create them all from the automation-friendly command line.
As an example of this in action, imagine trying to capture the processes running on a system when a problematic event occurs. That script might look like:
$logTag = "{0:yyyyMMdd_HHmm}" -f (Get-Date) $logPath = 'C:Program FilesTaskScriptsScriptEvents-{0}.txt' -f $logTag Start-Transcript -Path $logPath Get-WmiObject Win32_OperatingSystem | Format-List | Out-String Get-Process | Format-Table | Out-String Stop-Transcript
After generating an event, we can see the log being created just moments after:
PS > dir Directory: C:Program FilesTaskScripts Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 2/21/2010 8:38 PM 278 ScriptEvents.ps1 PS > Write-EventLog -LogName ScriptEvents -Source PowerShellCookbook ` -EventId 1010 -Message "Hello World" PS > dir Directory: C:Program FilesTaskScripts Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 2/21/2010 9:50 PM 12766 ScriptEvents-20100221_2150.txt -a--- 2/21/2010 8:38 PM 278 ScriptEvents.ps1
When
we define the task, we use the /TN
parameter to
define a name for our task. As the command (specified by the
/TR
parameter), we tell Windows to launch
PowerShell.exe with several parameters to customize
its environment. We use the /RL
parameter to ensure
that the task is run with elevated permissions (as it writes to the
Program Files directory). To define the actual
event log filter, we use the /EC
parameter to define
the event channel—in this case, the ScriptEvents
log.
In the /MO
(“modifier”) parameter, we specify the
XPath filter required to match events that we care about. In this case,
we search for EventId 1010. The System/
prefix
doesn’t tell Windows to search the System
event log;
it tells it to look in the standard system properties:
EventID
, Level
,
Task
, Keywords
,
Computer
, and more.
For more information about the event viewer’s XPath syntax, see Retrieve and Filter Event Log Entries.
Use the Limit-EventLog
cmdlet to manage the
retention policy (days, size, and overflow behavior) of an event log.
Use the Clear-EventLog
cmdlet to clear it
completely:
PS > Get-EventLog -List | Where-Object { $_.Log -eq "ScriptEvents" } Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 2,048 7 OverwriteOlder 872 ScriptEvents PS > Clear-EventLog ScriptEvents PS > Get-EventLog -List | Where-Object { $_.Log -eq "ScriptEvents" } Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 2,048 7 OverwriteOlder 0 ScriptEvents PS > Limit-EventLog -LogName ScriptEvents -MaximumSize 1024kb PS > 1..10000 | Foreach-Object { Write-EventLog -LogName ScriptEvents -Source PowerShellCookbook ` -EventId 1234 -Message ('A' * 1000) } PS > Get-EventLog -List | Where-Object { $_.Log -eq "ScriptEvents" } Max(K) Retain OverflowAction Entries Log ------ ------ -------------- ------- --- 1,024 7 OverwriteOlder 424 ScriptEvents
Both cmdlets support remote administration via
the -ComputerName
parameter.
While the default policies of most event logs are sensible, PowerShell still provides commands to help you manage how much information each event log retains.
For permanent policy changes, use the
Limit-EventLog
cmdlet. This cmdlet lets you limit the
log size, maximum event age, and overwrite behavior for the event log
that you apply it to. While the size and age limits are fairly
self-describing parameters, configuring the overflow behavior is more
subtle.
The -OverflowAction
parameter supports one of three options. Each describes a different
strategy for Windows to take when writing to a full event log:
To clear an event log entirely, use the
Clear-EventLog
cmdlet. If you want to save the
contents of the event log before clearing it, see Back Up an Event Log. PowerShell does not include a cmdlet
to clear the new event logs supported by Vista and later (as exposed by
the Get-WinEvent
cmdlet), but you can use the
[System.Diagnostics.
Eventing.Reader.
Event
Log
Session]::
GlobalSession.ClearLog()
method from the .NET Framework to clear these event logs. For more
information about working with .NET objects, see Work with .NET Objects.
If you want to remove an event log entirely, see Create or Remove an Event Log.
To access event logs on a remote machine, use
the -ComputerName
parameter of any of the
EventLog
cmdlets:
PS > Get-EventLog System -ComputerName LEE-DESK | Group-Object Source Count Name Group ----- ---- ----- 91 Print {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 640 TermServDevices {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 148 W32Time {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 100 WMPNetworkSvc {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 856 Service Control Manager {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... 123 Tcpip {LEE-DESK, LEE-DESK, LEE-DESK, LEE-DESK... (...)
To use the graphical event log viewer to
browse event logs on a remote machine, use the Show-EventLog
cmdlet:
Show-EventLog Computername
The -ComputerName
parameter
of the *-EventLog
cmdlets makes it easy to manage
event logs of remote computers. Using these cmdlets, you can create
event logs, remove event logs, write event log entries, and more.
If you want to use a graphical user interface
to work with event logs on a remote machine in a more ad-hoc way, use
the Show-EventLog
cmdlet. If the Remote Eventlog
Management firewall rule is enabled on the remote computer (and you have
the appropriate permissions), PowerShell launches the Windows Event
Viewer targeted to that machine (see Figure 23-1).
By default, the Windows Event Viewer tries to use the credentials of your current account to connect to the remote computer. If you need to connect as another account, click the “Connect to Another Computer” action on the righthand side of the Event Viewer window that opens. In that window, specify both the remote computer name and new user information.
For information about how to get event logs, see List All Event Logs. For more information about how to create or delete event logs, see Create or Remove an Event Log. For more information about how to write event log entries, see Write to an Event Log.
3.141.200.3