Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gets the final lines of a really big log file, and outputs them to a smaller, more manageable log file
Function Get-LastLogLines {
Param(
$FileName,
$Lines = 30
)
# Method borrowed and adapted from: https://stackoverflow.com/questions/36507343/get-last-n-lines-or-bytes-of-a-huge-file-in-windows-like-unixs-tail-avoid-ti
$result = ""
$seq = "`r`n"
$buffer_size = 10mb
$buffer = new-object Byte[] $buffer_size
$fs = [IO.File]::OpenRead($FileName)
while (([regex]::Matches($result, $seq)).Count -lt $Lines)
{
$fs.Seek(-($result.Length + $buffer_size), [System.IO.SeekOrigin]::End) | Out-Null
$fs.Read($buffer, 0, $buffer_size) | Out-Null
Write-Progress -Activity "Searching File" -Status "Searching at offset $(-($result.Length + $buffer_size)/1kb) kb"
$result = [System.Text.Encoding]::UTF8.GetString($buffer) + $result
}
$fs.Close()
($result -split $seq) | Select -Last $Lines
}
Get-LastLogLines -FileName "C:\AReallyBigMultipleGigabyteTextLogFile.log" -Lines 152 | Out-File -Encoding ascii -FilePath "C:\Users\Charles\Desktop\test.txt"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.