More Fun with Get-Content

A few followups on my recent post about Get-Content. First, you can also use the CAT alias if you’re used to the Unix world, or TYPE in place of get-content. The Get-Content cmdlet does have a parameter called -totalcount that will return the specified number of lines from the beginning of the file:

cat c:\boot.ini -totalcount 3

Unfortunately, you can’t specify a range or start at the end of the file. However, there is a way to simplify the one-liner I used. You can use the built in common parameters and specify a variable with Get-Content. This command will get the last five lines of the file log.txt:

cat log.txt -outvariable c >$null ; $c[($c.count-5)..($c.count)]

I’m redirecting the output of the first half of the expression to $null otherwise I’d see the entire file in addition to the last five lines.

That is much more efficient. Now I don’t have to get the count or length ahead of time. And if you wanted to wrap this up in a function, it is pretty simple:

Function GetTail {
param([string]$file,[int]$lines)
cat $file -outvariable c >$null ; $c[($c.count-$lines)..($c.count)]

}

To use:

GetTail log.txt 5

Will return the last five lines of log.txt.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to StumbleUpon

This entry was posted in PowerShell, Scripting and tagged , . Bookmark the permalink.

3 Responses to More Fun with Get-Content

  1. Jeffery Hicks says:

    Here’s an even more efficient function:
    Function GetTail {
    param([string]$file,[int]$lines)
    (cat $file)[-$lines..-1]
    }

    Thanks to Vinicius Canto for the tip.

  2. Dus says:

    I have an excel document that has 7 columns and I want to get the last column of data. How do you specify which column you want get-content to pull from?

  3. Jeffery Hicks says:

    dus,
    You can only use Get-Content with text files. To work with Excel you would need to use the Excel COM object just as you would with VBScript, although with PowerShell it can be interactive. If you can save your data as a CSV you could also use the Import-CSV cmdlet. Each line would be an object. Its properties would be the column headings. You would use something like:

    import-csv mydata.csv | Select myproperty