- How to configure computer delegation with PowerShell - Mon, Jul 23 2018
- Save on Azure costs for testing and training - Wed, Jun 6 2018
- Clean up orphaned Foreign Security Principals - Fri, Oct 20 2017
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.
Get-Content -Path C:\Windows\System32\LogFiles\HTTPERR\httperr1.log
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 -Path 'C:\Program Files\Update Services\LogFiles\SoftwareDistribution.log' |Out-Host –Paging
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.
Get-Content -Path C:\Windows\Logs\DISM\dism.log -Tail 50
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 -Path C:\Windows\WindowsUpdate.log -Tail 5 –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.
Select-String -Path C:\Windows\System32\LogFiles\Firewall\pfirewall.log ‑Pattern 'Drop' | Select-Object -Last 20
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.
Select-String -Path C:\Windows\WindowsUpdate.log -Pattern 'error','warning'
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.
Select-String C:\Windows\Cluster\Reports\Cluster.log -Pattern ' err ' ‑Context 3
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.
Get-Content C:\Windows\debug\netlogon.log |Select-Object -First 30 -Skip 45
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.
Subscribe to 4sysops newsletter!
PSEdit C:\inetpub\logs\LogFiles\W3SVC1\u_ex170723.log
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
@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}
Thanks for this article.
FYI, PSEdit works with the integrated terminal in VS Code; assuming you have the PowerShell extension installed.
Ugh. Only works for local files not in a PSSession.
@tmack
Did you open a New Remote Powershell tab in ISE?
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!
@Pat
You are right.
I have updated the post.
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.
@tmack
The post has been updated about PSEdit and also the 3 lines instead of 5.
Thanks!
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.
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.
@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"}
Hi Luc,
i have tried the same using last.accesstime as well but it still generated false alarm eventhough the file is modified
@prasad bhilare
What do you mean with “false alarm”?
Is the LastWriteTime property updated while the file content didn’t change?
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?
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.
Hi Richard,
What do you mean with “Windows notification”?
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
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.
Luc fullenworth,
i need to monitor the log file in regular interval, there is no timestamp in logfile. I gone through your comment on copying the old logfile and comparing with the new logfile. If you have a code can you share it to my email id "prasadengg2006@gmail.com ?
Thanks,
Prasad.B
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.
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!
🙂
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 ?
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
@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:
Then sending a mail is really the easiest part…
Please I will like to know a PS command that displays logs from a backup file with it's content showing text of most recent logs on top then old text at the bottom of the text. Most logs starts with older files on top, one has to scroll all the way down to view recent log. Thank you