Powershell: Selecting files that don’t contain specified content

I had a quick task today that required that I search a couple hundred directories and look in specific files to see if they contained a certain piece of code. All I wanted was the list of files that did not. PowerShell to the rescue!

I’ll break down each of the calls I used and provide the full command-line at the end for anyone interested.

First, we need to recurse through all the files in a specific directory. This is simple enough using Get-ChildItem.

Get-ChildItem -include [paths,and,filenames,go,here] -recurse

Next, I needed to loop through each of those files using ForEach-Object :

ForEach-Object { … }

Next, I need to get the content of each of those files. That’s done using Get-Content:

Get-Content [file]

I then need to be able to determine if the contents of the file contains the string I’m looking for. This is easy enough with Select-String:

Select-String -pattern [pattern]

That’s pretty much all the commands you need to know — we just need to put them together now.

PS> Get-ChildItem -include *.html,*.xhtml -recurse |
    ForEach-Object { if( !( select-string -pattern "pattern" -path $_.FullName) ) 
                     { $_.FullName}}
Be Sociable, Share!

    5 Thoughts on “Powershell: Selecting files that don’t contain specified content

    1. Cédric Rup on February 8, 2012 at 11:48 pm said:

      There’s simplier :
      Get-ChildItem -include *.html,*.xhtml -recurse | select-string -pattern “pattern” | select-object Path -unique

      • Cedric, thanks for the reply and the great suggestion. However, your demo only shows files that DO contain a given piece of text. It is often necessary to search directories for files that do NOT contain the specified text. That’s what this post was about. If you are looking for files that do contain a specified bit of text, you can always just use the old “find” command, or the sample that you provided. If you know of a more simple way to search for files that do not contain the specified pattern, please let me know! Thanks again!

    2. Cédric Rup on February 9, 2012 at 12:03 am said:

      My bad, I read too quickly. My line show files that contains the pattern
      Guess we can do something to exclude files from a list, but it may be less effective.
      Please feel free to ignore my comments.

    3. Ah, I was typing my response as you posted this. My apologies as well. No need to worry. I sincerely appreciate the response. And if you do find something simpler, please let me know!

    4. A Hooper on September 23, 2013 at 2:32 pm said:

      plus you can put -quiet on the select-string

    Leave a Reply

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

    Post Navigation