If you have to find information in unstructured log files, PowerShell offers a variety of cmdlets that can help you parse text files to extract the information you need.

Luc Fullenwarth

Luc is working as a system administrator since 1999 at Alcatel-Lucent, at HP, and currently for an European institution. He focuses on Active Directory, Group Policy, security and PowerShell.

In my last article, I showed you how to search the Windows Event Log with Get-WinEvent. That's where you usually spot most of the pertinent messages. However, sometimes you also need to reference log files in textual format. For example, this is the case for the Windows Update log or the Firewall log.

Displaying the content of a log file ^

The Get-Content cmdlet can be useful in many situations, such as when displaying text or log files.

For instance, the following command line displays the whole content of the httperr1.log file.

Displaying long log files ^

Some log files are very long, and if you want to display them one page at a time, just pipe the content to the Out-Host cmdlet along with the -Paging parameter.

Please note that this option is not available in the Integrated Scripting Environment (ISE) console.

For example, the following command displays the Windows Server Update Services (WSUS) SoftwareDistribution log one page at a time.

Get Content with paging output

Get Content with paging output

Displaying only the end of a log file ^

However, usually the last lines are the most relevant ones because they contain either the global success messages or fatal errors. Thus, it's sometimes useful to view only the final lines of log files.

For instance, the following command displays the last 50 lines of the Deployment Image Servicing and Management (DISM) log file.

Because some services write continuously to a log file, you may want to display new lines as soon as they appear. That's exactly the purpose of the -Wait parameter.

In this case, Get-Content continues to wait for new lines and displays them on the fly until you hit Ctrl+C.

Please note that Get-Content still continues to wait for new lines even when the process or service writing to the file has already stopped.

In the next example, the command line displays the last five lines of the WindowsUpdate.log and waits for additional lines to display.

Get Content and wait

Get Content and wait

There's a blinking underscore on that last screen. This means the cmdlet is waiting for new lines to display.

Displaying only specific lines ^

In some cases, you may want to display only lines containing specific words.

If you want to search for packets the firewall has dropped, you can use the command below. This searches all lines from the firewall log containing the word "Drop" and displays only the last 20 lines.

Fortunately, the -Pattern parameter accepts arrays as input, and you can provide several patterns to search. All patterns are processed with the logical OR operator.

For instance, the following command displays lines containing the word "error" or the word "warning" from the Windows Update agent log file.

Displaying only specific lines inside their context ^

Sometimes you may also want to know in which context the pattern appears.

For this purpose, Select-String has another interesting parameter named -Context, which shows you the lines before and after the string matching the pattern.

The following command searches for lines with the word "err" preceded and followed by a space. It also displays the three lines before and after every match from the cluster log file.

Searching with Select String

Searching with Select String

The last screenshot shows that the line containing the pattern starts with a greater than symbol. But you can also see that the Select-String cmdlet displays the line number of the log file for each hit.

Thus, if you spotted a specific line in the midst of log file, you can display only the context for this specific line by using the Get-Content cmdlet and piping the result to the Select-Object cmdlet associated with the First and Skip parameters.

For instance, the following command line displays lines 45 to 75 from the netlogon.log file.

Opening a remote file ^

With all of that, if you still want to open the log file in a GUI, you can run PSEdit in a PSSession. This command directly opens the file without the need to download it locally first.

Please note that PSEdit is only available in the ISE console.

For example, the following command line downloads and opens the log file of the default IIS website.

Join the 4sysops PowerShell group!

1+
Share

Related Posts

24 Comments
  1. Gtech 2 years ago

    how do I get remote server process list (single liner not script) and to kill the specific process.What I have gone through that try the invoke command which is I am not getting why so. Can you advise with right cmdlt.Thankx

    1+

    • Author
      Luc Fullenwarth 2 years ago

      @Gtech

      This is out of scope of the current post, but what you are searching is:

      Invoke-Command -ComputerName MyComputer -ScriptBlock {Get-Process -Name 'ProcessName' |Stop-Process}

      1+

  2. tmack 2 years ago

    Thanks for this article.

    FYI, PSEdit works with the integrated terminal in VS Code; assuming you have the PowerShell extension installed.

    2+

    • tmack 2 years ago

      Ugh. Only works for local files not in a PSSession.

      1+

  3. Pat 2 years ago

    When describing Context, you mention "displays the five lines before and after every match".  Don't you mean 3 lines?  "-Context 3" ?

    Or am I misunderstanding the purpose of the 3?

    Great article, thanks!

    3+

    Users who have LIKED this comment:

    • avatar
  4. tmack 2 years ago

    I did not try ISE as I use VS Code exclusively. You say it works so I'll take your word for it. I was just posting so others would know this does not work with VS Code.

    2+

    Users who have LIKED this comment:

    • avatar
    • Author
      Luc Fullenwarth 2 years ago

      @tmack
      The post has been updated about PSEdit and also the 3 lines instead of 5.
      Thanks!

      1+

  5. tmack 2 years ago

    Likely pared the example down to 3 lines from 5 in order to fit the screenshot and forgot to go back and edit the text of the article.

    2+

    Users who have LIKED this comment:

    • avatar
  6. prasad bhilare 1 year ago

    Hi Luc,

    i am trying to write a script using powershell to generate a message when file is not modified for more than 5 Min however as you are aware the time stamp of the log file does not modifies until it is closed. so is there any way i can check if log file (log4net )is not modified for more than 5 min.

    1+

  7. Author
    Luc Fullenwarth 1 year ago

    @prasad bhilare

    Open a test file with Notepad.
    Change the content and click Save but keep the file open.
    As you can notice, the file's timestamp has been updated despite the file is still open.

    Anyway, if you want to monitor if your file has changed since the last five minutes, you can schedule a task every five minutes with a PowerShell script which could look like this:

    if((Get-Item -Path C:\PathToMyFile\MyLogFile.txt).LastWriteTime -gt (Get-Date).AddMinutes(-5)){"doing my stuff here"}

    1+

    • prasad bhilare 1 year ago

      Hi Luc,

      i have tried the same using last.accesstime as well but it still generated false alarm eventhough the file is modified

      1+

      • Author
        Luc Fullenwarth 1 year ago

        @prasad bhilare

        What do you mean with "false alarm"?

        Is the LastWriteTime property updated while the file content didn't change?

        1+

        • prasad bhilare 1 year ago

          Hi Luc,

          Apologies for late response , this is little strange but i found that the file is getting updated continuously however the lastwrite time and even lastacess time doesn't change. is there any way i can add screen shots here for more details?

          1+

  8. Richard O. 10 months ago

    Hi,

    I'm interested if there's a way to show a Windows notification when a line appears in a log file, for example something like "Server started".

    Thanks.

    1+

    • Author
      Luc Fullenwarth 10 months ago

      Hi Richard,

      What do you mean with "Windows notification"?

      2+

      • Richard Oszlanczi 10 months ago

        Hi Luc,

        I mean a notification in the Windows 10 taskbar notification area, like the ones I get when a Skype message or a new email arrives.

        Thanks,
        Richard

        1+

        • Author
          Luc Fullenwarth 10 months ago

          For this type of notification you can use the System.Windows.Forms.NotifyIcon object.
          Just search on google for PowerShell Balloon Notifications.

          For the permanent monitoring of the file, I would use either the While method, or a scheduled task triggered every X minutes.

          And concerning a way to check the file content, if there is a timestamp at the beginning of every line, just parse the lines written since the last check (X minutes). Or if there is no timestamp, create a copy of the file and compare the last copy (X minutes old) to the new current version to extract the new lines and find your pattern.

          1+

  9. David Figueroa 10 months ago

    Richard O..

    There is a module out on PSGallery called BurntToast to send those kind of notifications. The only tricky part right now is the module only works for the current user's context, you can't send the toasts into a different session/security context.  The author is working on finding a way to do that.  (I had chatted with him after an online user group presentation for it).

    https://www.powershellgallery.com/packages/BurntToast/0.6.2

    David F.

    2+

    Users who have LIKED this comment:

    • avatar
  10. Jim Ruby 10 months ago

    Seems like every time I cobble up a Powershell solution to a problem, along comes some wise guy who shows me I did it the hard way.  Thanks - like it or not you've made my job a little easier today, but don't tell my boss, he likes to see me sweating over complex solutions!

    🙂

     

    2+

    Users who have LIKED this comment:

    • avatar
  11. Joe Fernandes 5 months ago

    Luc how can I forward an alert popup notification that shows-up on my desktop to my e-mail with Windows powershell ......is that possible ?

    0

  12. David Figueroa 5 months ago

    Joe F:

    One thing you can do is use the built-in msg.exe command in your script to send a popup. It won't be a toaster notification, but it does not care about the session (in fact, it uses the session).  You may be able to use a System  Tray Notification, but I'm not sure about the ability to send to a different user's session for that.

    As an example:

    Coralon

    1+

  13. Author
    Luc Fullenwarth 5 months ago

    @Joe Fernandes

    Your question is not really related to the topic of the post.
    It would be more appropriate in the PowerShell forum.

    However, are you talking about Pop-up messages or notification balloons from the task bar?

    In any case, I don't see an easy solution for that.

    You have to parse all processes for their properties to find those who are displaying messages.
    But this is a task for a developer 🙂

    Furthermore, your approach is an end user approach working on a workstation.

    I would suggest a SysAdmin approach working with servers:

    • configure your application to log what you want to find in the event log
    • configure the Audit policy accordingly

    Then sending a mail is really the easiest part...

    1+

Leave a reply

Your email address will not be published. Required fields are marked *

*

CONTACT US

Please ask IT administration questions in the forum. Any other messages are welcome.

Sending
© 4sysops 2006 - 2019

Log in with your credentials

or    

Forgot your details?

Create Account