Often in PowerShell you may want to use the Select-String cmdlet to only return the first line in a file that matches a specific pattern.
You can use the following syntax to do so:
(Select-String "Nuggets" data.txt).line | Select-Object -First 1
This particular example returns only the first line in the file named data.txt that contains the pattern “Nuggets” somewhere in the line.
Note that we use the line property to return only the text from the matching line.
If we’d like, we could instead use the linenumber property to only return the number of the first line that matches the pattern:
(Select-String "Nuggets" data.txt).linenumber | Select-Object -First 1
The following example shows how to use this syntax in practice.
Example: Use Select-String and Only Return First Match in PowerShell
Suppose that we have a file named data.txt that contains information about various basketball players.
We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to return the first line in that file that matches the pattern “Nuggets” somewhere in the line.
We can use the following syntax to do so:
(Select-String "Nuggets" data.txt).line | Select-Object -First 1
The following screenshot shows how to use this syntax in practice:

Notice that this returns the text from only the first line in the file that matches the pattern we specified.
Note that we could also use the following syntax to only return the line number of the first line that matches the pattern:
(Select-String "Nuggets" data.txt).linenumber | Select-Object -First 1
The following screenshot shows how to use this syntax in practice:

This returns the value 5, which tells us that the first line that contains the pattern “Nuggets” in the file is line number 5.
Note: You can find the complete documentation for the Select-String cmdlet in PowerShell here.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: Use Select-String to Search for Multiple Patterns
PowerShell: Use Select-String to Recursively Search for Strings
PowerShell: Use Select-String and Exclude Specific Pattern
