Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DISTINCT Select-String output on directory/text search

I am curious how to produce a distinct file list based on this example.

** This example produces a list of all .ps1 and .psm1 files that contain the text "folders", but without the text ".invoke" on the same line.

$text='folders'
dir C:\Workspace\mydirectorytosearch1\ -recurse -filter '*.ps*1' | Get-ChildItem | select-string -pattern $text | where {$_ -NotLike '*.invoke(*'}
dir C:\Workspace\mydirectorytosearch2\ -recurse -filter '*.ps*1' | Get-ChildItem | select-string -pattern $text | where {$_ -NotLike '*.invoke(*'}

This is cool and works well but I get duplicate file output (same file but different line numbers).

How can I keep my file output distinct?

The current undesirable output:

  • C:\Workspace\mydirectorytosearch1\anonymize-psake.ps1:4:. "$($folders.example.test)\anonymize\Example.vars.ps1"
  • C:\Workspace\mydirectorytosearch1\anonymize-psake.ps1:5:. "$($folders.missles)\extract\build-utilities.ps1"

The desired output:

  • C:\Workspace\mydirectorytosearch1\anonymize-psake.ps1

Help me tweak my script??

like image 395
D3vtr0n Avatar asked Oct 31 '12 15:10

D3vtr0n


People also ask

How do I find a specific String in PowerShell?

You can use Select-String similar to grep in UNIX or findstr.exe in Windows. Select-String is based on lines of text. By default, Select-String finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match.

How do I select multiple strings in PowerShell?

Use Select-String Cmdlet in Windows PowerShell If we want to search for multiple patterns, we can separate the parameter values with a comma under the Pattern parameter.

Can you use grep in PowerShell?

When you need to search through a string or log files in Linux we can use the grep command. For PowerShell, we can use the grep equivalent Select-String . We can get pretty much the same results with this powerful cmdlet. Select-String uses just like grep regular expression to find text patterns in files and strings.


1 Answers

You can eliminate duplicates wit Select-String and the Unique parameter:

$text='folders'
Get-ChildItem C:\Workspace\mydirectorytosearch1\,C:\Workspace\mydirectorytosearch2\ -Recurse -Filter '*.ps*1' |
Select-String -Pattern $text | Where-Object {$_ -NotLike '*.invoke(*'} | 
Select-Object Path -Unique
like image 50
Shay Levy Avatar answered Nov 15 '22 03:11

Shay Levy