powershell

Find specific String in Textfile


I know this question might be a "new guy question" but I probably made a logical mistake.

I have a text file and I want to search if it contains a string or not. I tried it as shown below but it doesn't work:

$SEL = "Select-String -Path C:\Temp\File.txt -Pattern Test"
if ($SEL -eq $null)
{
    echo Contains String
}
else
{
    echo Not Contains String
}

Solution

  • 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.