PowerShell: How to Check if File Contains Specific String


You can use the following basic syntax in PowerShell to check if a file contains a specific string:

if (Select-String -Path c:\docs\my_data.csv -Pattern "this" -SimpleMatch -Quiet)
{
echo "String Exists in File"
}
else
{
echo "String Does Not Exist in File"
}

This particular example checks if the file named my_data.csv contains the string “this” anywhere in the file.

If the file contains “this” then String Exists in File will be returned.

If the file does not contain “this” then String Does Not Exist in File will be returned.

The following example shows how to use this syntax in practice.

Example: How to Check if File Contains Specific String in PowerShell

Suppose we have the following CSV file named basketball_data.csv that contains information about the number of points, assists and rebounds for various basketball players:

Suppose that this file is saved in the following location:

  • c:\users\bobbi\basketball_data.csv

Suppose that we would like to check if the string “rebounds” exists anywhere in the file.

We can use the following syntax to do so:

if (Select-String -Path c:\users\bobbi\basketball_data.csv -Pattern "rebounds" -SimpleMatch -Quiet)
{
echo "String Exists in File"
}
else
{
echo "String Does Not Exist in File"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if file contains string

PowerShell returns String Exists in File since the string “rebounds” does indeed exist in the CSV file.

Suppose instead we searched for the string “steals”, which does not exist in the file:

if (Select-String -Path c:\users\bobbi\basketball_data.csv -Pattern "steals" -SimpleMatch -Quiet)
{
echo "String Exists in File"
}
else
{
echo "String Does Not Exist in File"
}

The following screenshot shows how to use this syntax in practice:

PowerShell returns String Does Not Exist in File since the string “steals” does not exist in the CSV file.

Note: We used the -Quiet operator to specify that the file should stop being searched once the first occurrence of the string of interest has been detected. This speeds up the process.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String
PowerShell: How to Concatenate Strings

Leave a Reply