Loading...
X

How to monitor new lines in a file in PowerShell

How to set up notifications for new lines in a file

If you need to monitor logs (journals) in which new lines appear, then Windows has a convenient tool for this. You do not need to install or configure anything additionally – everything you need is already available on all current versions of Windows.

You can monitor the appearance of new lines in a file using the PowerShell cmdlet. If you run the Get-Content cmdlet with the -Wait option, the existing contents of the file will be displayed, but the cmdlet will not stop working. The -Wait option makes the cmdlet wait indefinitely, leaving the file open until the command is stopped. While waiting, Get-Content checks the file once a second and displays new lines, if any.

Get-Content syntax for monitoring file changes:

Get-Content FILE -Wait

The following example will display the contents of the access.log file located in the C:\Server\bin\Apache24\logs\ folder, after which the program will continue to run and output newly added lines:

Get-Content C:\Server\bin\Apache24\logs\access.log -Wait

See also: How to read file contents in PowerShell. How to save file contents to a variable

When any line is deleted from a file, the entire file is displayed again.

When used with the -TotalCount parameter, Get-Content waits until the specified number of lines are available in the specified file. For example, if you specify -TotalCount equal to 10 and the file already contains 10 or more lines, Get-Content returns 10 lines and exits. If the file has fewer than 10 lines, Get-Content prints each line as it comes in, but waits until the 10th line appears before exiting.

You can interrupt (stop) -Wait by pressing Ctrl+c. Deleting a file causes an error, which also interrupts the cmdlet.

How to monitor new entries in multiple files

You can specify multiple files as a comma-separated option to Get-Content, for example:

Get-Content FILE1,FILE2,FILE3,FILE4 -Wait

But with the -Wait option, this command will not work as you expect – only the contents of the first file will be printed. Overall, this looks like a bug.

However, you can achieve a similar result – monitoring multiple log files – by simply opening multiple terminals and running Get-Content in each of them, specifying the file you are interested in, for example:

Get-Content FILE1 -Wait
Get-Content FILE2 -Wait

Leave Your Observation

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