How to search a string in multiple files and return the names of files in Powershell?

后端 未结 11 1884
野的像风
野的像风 2020-11-30 15:57

I have started learning powershell a couple of days ago, and I couldn\'t find anything on google that does what I need so please bear with my question.

I have been a

11条回答
  •  盖世英雄少女心
    2020-11-30 16:37

    There are a variety of accurate answers here, but here is the most concise code for several different variations. For each variation, the top line shows the full syntax and the bottom shows terse syntax.

    Item (2) is a more concise form of the answers from Jon Z and manojlds, while item (1) is equivalent to the answers from vikas368 and buygrush.

    1. List FileInfo objects for all files containing pattern:

      Get-ChildItem -Recurse filespec | Where-Object { Select-String pattern $_ -Quiet }
      ls -r filespec | ? { sls pattern $_ -q }
      
    2. List file names for all files containing pattern:

      Get-ChildItem -Recurse filespec | Select-String pattern | Select-Object -Unique Path
      ls -r filespec | sls pattern | select -u Path
      
    3. List FileInfo objects for all files not containing pattern:

      Get-ChildItem -Recurse filespec | Where-Object { !(Select-String pattern $_ -Quiet) }
      ls -r filespec | ? { !(sls pattern $_ -q) }
      
    4. List file names for all files not containing pattern:

      (Get-ChildItem -Recurse filespec | Where-Object { !(Select-String pattern $_ -Quiet) }).FullName
      (ls -r filespec | ? { !(sls pattern $_ -q) }).FullName
      

提交回复
热议问题