Search code examples
powershelltext

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.

Select-String -Pattern "TextThatIsInMyFile" -Path c:\Stuff\batch\*.txt

Add-Content -Path "c:\Stuff\batch\*.txt" -Value "`r`nThis is the last line"

Solution

  • 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.

    Get-ChildItem "C:\Stuff\Batch\*" -Include *.jsp,*.sh,*.cmd -File | 
        Where{!(Select-String -SimpleMatch "TextThatIsInMyFile" -Path $_.fullname -Quiet)} |
        ForEach{
            $Path = $_.FullName
            "TextThatIsInMyFile",(Get-Content $Path)|Set-Content $Path
        }
    

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

        Get-ChildItem "C:\Stuff\Batch" -Include *.jsp,*.sh,*.cmd -File -Recurse