Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Created November 29, 2019 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indented-automation/78634ebcecf4504bc8126ba6d47ccc78 to your computer and use it in GitHub Desktop.
Save indented-automation/78634ebcecf4504bc8126ba6d47ccc78 to your computer and use it in GitHub Desktop.
Export an event log to an evtx file.
function Export-EventLog {
<#
.SYNOPSIS
Export an event log to a saved event log file.
.DESCRIPTION
Export an event log, and it's messages, to a named event log file.
.EXAMPLE
Get-WinEvent -ListLog Application | Export-EventLog
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[string]
$LogName,
# If not set, a file named after the event log is created.
[Parameter(ValueFromPipelineByPropertyName)]
[string]
$Path,
[string]
$Query = '*',
[PSCredential]
$Credential,
[string]
$ComputerName = $env:COMPUTERNAME,
[System.Globalization.CultureInfo]
$Culture = (Get-Culture)
)
begin {
if ($Credential) {
$username, $domain = $Credential.Username
if (-not $username) {
$username = $domain
$domain = $ComputerName
}
$eventLogSession = [System.Diagnostics.Eventing.Reader.EventLogSession]::new(
$ComputerName,
$username,
$domain,
$Credential.Password,
'Default'
)
} elseif ($ComputerName -eq $env:COMPUTERNAME) {
$eventLogSession = [System.Diagnostics.Eventing.Reader.EventLogSession]::new()
} else {
$eventLogSession = [System.Diagnostics.Eventing.Reader.EventLogSession]::new($ComputerName)
}
}
process {
if (-not $Path) {
$name = '{0}.evtx' -f $LogName -replace '/', '_'
$Path = Join-Path -Path $pwd -ChildPath $name
}
try {
Write-Verbose ('Exporting event log {0} to {1}' -f $LogName, $Path)
if (Test-Path $Path -PathType Leaf) {
Remove-Item $Path -ErrorAction Stop
}
$eventLogSession.ExportLogAndMessages(
$LogName,
'LogName',
$Query,
$Path,
$true,
$Culture
)
} catch {
Write-Error -ErrorRecord $_
}
}
end {
$eventLogSession.Dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment