Find specific String in Textfile - Powershell

i think this is what you are trying to do:

$SEL = Select-String -Path C:\Temp\File.txt -Pattern "Test"

if ($SEL -ne $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}

In your example, you are defining a string called $SEL and then checking if it is equal to $null (which will of course always evaluate to false, because the string you define is not $null!)

Also, if the file contains the pattern, it will return something like:

C:\Temp\File.txt:1:Test

So make sure to switch your -eq to -ne or swap your if/else commands around, because currently you are echoing Contains String when the $SEL is $null, which is backwards.

Check SS64 for explanations and useful examples for everything in PowerShell and cmd


Another way of checking if a string exists in the file would be:

If (Get-Content C:\Temp\File.txt | %{$_ -match "test"}) 
{
    echo Contains String
}
else
{
    echo Not Contains String
}

but this doesn't give you an indicaion of where in the file the text exists. This method also works differently in that you are first getting the contents of the file with Get-Content, so this may be useful if you need to perform other operations on those contains after checking for your string's existence.


modify your quote string like this and use simplematch for dont use regex search and -Quiet for return a boolean and dont search in all file (better for performance)

if (Select-String -Path C:\Temp\File.txt -Pattern "test" -SimpleMatch -Quiet)
{
echo "Contains String"
}
else
{
echo "Not Contains String"
}

Tags:

Powershell