Created
November 29, 2019 18:27
-
-
Save indented-automation/78634ebcecf4504bc8126ba6d47ccc78 to your computer and use it in GitHub Desktop.
Export an event log to an evtx file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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