Powershell add text to files if does not exist


I would like to create a Powershell script that adds text to *.jsp *.sh *.cmd files. I would also like it to check if the text already exist in that file and if it does then it skips the file. So far I have found Select-String which will find the text in the file. How do I then use this information to add text to top of the files that do not have the text in them? I also found Add-Content which seems to add the content I want but I would like to do it at the beginning and have some logic to not just keep re-adding it every time I run the ps1.


Very similar to what @MikeWise has, but a little better optimized. I have it pulling the data and making the provider filter the files returned (much better than filtering afterwards). Then I pass it to a Where statement using Select-String‘s -quiet parameter to provide boolean $true/$false to the Where. That way only file that you want to look at are even looked at, and only those missing the text you need are altered.

Edit: As you discovered the \* does not work with -Recursive. Use the following if you need to recurse:


Powershell add text to files if does not exist by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply