Skip to content

Instantly share code, notes, and snippets.

@crossan007
Created May 15, 2019 17:55
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 crossan007/b5e8ac4579ba61eb1967315657406751 to your computer and use it in GitHub Desktop.
Save crossan007/b5e8ac4579ba61eb1967315657406751 to your computer and use it in GitHub Desktop.
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