How To Find A String in a File With PowerShell


So you have a need to have PowerShell to look for a string in a file and create and entry if it doesn’t find it and do nothing if it does.  For my example I am installing an application and I need to add three lines of content, but if it exists I do not want duplicate entries created.

The Code

There are probably other ways to achieve the goal, but my idea was to use Get-Content and read the file and search for  my string. The goal is to use variables where we can, to make the code easily re-usable, find our string and if not found add a few lines.

We will create two variables, one called $FileName for the file to search and one called $wordToFind and define them.

Now we are ready to use If statement to with Get-Content to search for our string. If found just write out nothing needed to be done and leave, but if not found add a few lines to the file.

Not much to it. Script does exactly as planned  and is re-usable due to the variables.


By using the Get-Content cmdlet with If statement we were able to look for a string in a file and add or do nothing.

Leave a Reply

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