Dan's profileda.nfin.chBlogLists Tools Help

da.nfin.ch

programming stuff
my articles
August 21

hacks: powershell tail function

This is my first blog post. It is a powershell script I wrote for my coworker when SQL Server figured it would be cool to make a log file that was several hundred GB. I went on a short description of Unix' "tail". I didn't help much as the script doesn't work on SQL Server log files. It works with everything else I tried, though. Hopefully eventually somebody will google this page and save themselves some time. Let me know if I screwed up, and more importantly, how.

Usage: tail <file> <howManyLines>

function tail( $file, $n = 1 ) {
    $stream = new-object system.io.fileStream( $file, [system.io.fileMode]::open, [system.io.fileAccess]::read )
    $line = new-object system.text.stringBuilder
    $lines = @()
    for ( $p = -2; $p -gt 0 - $stream.length; $p -= 2 ) {
        $empty = $stream.seek( $p, [system.io.seekOrigin]::end )
        $bytes = [byte[]]( $stream.readByte(), $stream.readByte() )
        $chars = [system.text.asciiencoding]::ascii.getchars( $bytes )
        [array]::reverse( $chars )
        foreach ( $char in $chars ) {
            $empty = $line.insert( 0, $char )
        }
        $l = $line.toString()
        if ( $l.contains( [environment]::newline ) ) {
            $lines = @( $l.substring( $l.indexOf( [environment]::newline ) + 2 ) ) + $lines
            $line = new-object system.text.stringbuilder( $l.substring( 0, $l.indexOf( [environment]::newline ) ) )
        }
        if ( $lines.length -ge $n ) {
            $stream.Close()
            return $lines
        }
    }
    $stream.Close()
    return $lines
}
 
my connections