PowerShell Tail Command


In a recent customer conversation, they were excited that PowerShell 5.0 would contain the option to tail a log file.  While they were excited to get that feature, they were less excited to hear that PowerShell 3.0 had already added the –Tail parameter to the Get-Content cmdlet.  Previously there have been other solutions to get this functionality, but is now native in PowerShell.

As an example:

Gets the last two lines of the log file:

Get-Content  .\u_ex160511.log -Tail 2

 

Gets the last two lines of the log file, and waits for more.

Get-Content  .\u_ex160511.log -Tail 2 –Wait

Let’s look at a quick example of the latter command.  In the below example, we are seeing the last two lines in an IIS log.  Since the –Wait parameter was added Get-Content will wait for new lines to be written to the file.

PowerShell Tail Command - Waiting For Additional Content

 

Shorty after, there is a connection to a health mailbox.  Note that the new lines were simply added to the screen and we did not have to re-issue the PowerShell command.

PowerShell Tail Command - Just like Buses, Two Come At Once....

For the Exchange admins out there, please ensure that the versions of .NET Framework and PowerShell installed on the Exchange servers are listed in the support matrix.

Cheers,

Rhoderick

Comments (8)

  1. The first time I used this, I cried.

    1. Long long time ago, I can still remember, how that cmdLet used to make me cry.

      1. Been listening to classic rock FM again? 🙂

        Cheers,
        Rhoderick

  2. cebundy408 says:

    Can you follow the file when it "rolls over" to a new file?

    1. I don't believe that is possible, Would be neat, though it would be hard to determine what that new file is especially it there is a random aspect to the name.

      Cheers,
      Rhoderick

  3. James says:

    Any ways of running this with -wait and if string is matched in the log, trigger an action?

    1. Chris L says:

      Ohh this is what I am looking for too. If a string is matched, trigger an action. That way I can tail a log looking for a specific error and for example have a service restart if true.

      1. Good Sam says:

        You can do something like this:

        Get-Content MyLogFile.log -Tail -2 -Wait | ? { $_ -like '*WHAT I'M LOOKING FOR*' } | % { RestartTheService }

        This will only pass through matches from the files that contain WHAT I'M LOOKING FOR and if there are none then the RestartTheService code won't get executed.

Skip to main content