select-string how to only return first match line in first file

Sheen picture Sheen · Aug 19, 2014 · Viewed 32k times · Source

I am searching a directory for pattern, switches are -SimpleMatch -List. But it returns a list of files. How to do it to return only first file and first line in it?

Answer

bouvierr picture bouvierr · Aug 19, 2014

Just use the Select-Object command to return the first match. You don't need to use Get-ChildItem since you can specify the path parameter in Select-String. The Select-String command returns MatchInfo object which contains the matching line and also the name of the file.

$m = Select-String -Pattern get -Path *.ps1 -list -SimpleMatch | select-object -First 1
$m.Line
$m.Path