Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions Links


SQL Server DBA Jobs

Powershell monitor log file for string with select-string and regex

25 April,2017 by Tom Collins

Question: I am trying to monitor a log file – used by a third party software. It is a text file where results are dumped if a file transfer is successful. I want to use a powershell script to parse the log file and check if a certain string exists.

I already have the scheduling and communication aspect of the job in place.

I want to return all the lines which match the criteria , and then only the part of the line which is relevant.

For example:

12 May 2017 the file myBACKUPfile.BAK was transferred to the target destination

I want to return the text file myBACKUPfile.BAK

How can I use powershell to get this result?


Answer: Powershell has a cmdlet called select-string. Combining select-string with regex is a good basis to start. There are alternative ways of getting the same results.But in terms of simplicity and functionality – this method is effective

Here is an example of a line of Powershell code.

get-content "N:\mypath\myfile.txt"|select-string "^(?!.*(file)).*[a-zA-Z0-9].BAK"


This code grabs the content with the get-content cmdlet. We are asking for some action to occur on this content. The select-string cmdlet is used to search for a text pattern between two words.

In this case I’m using regular expressions to apply the pattern, The two words are “file” and “.BAK” .

In summary , the code is consuming a file , and then searching for a text pattern between two words and returns a list.

You may then want to push to another file and  Send email from Powershell with attachment  or place into a database etc



Author: Tom Collins (


Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.


Post a comment on Powershell monitor log file for string with select-string and regex | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer