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 }
Python String find() method. Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With