1

I have a text 'File.txt'. There are 100's of lines. The file contains the string 'XX' (in any line), 'YY' (in any line) and 'ZZ' (in any line).
I want to check if the text file really contains 'XX' or 'YY' or 'ZZ'. If it yes then exit the script.
I'm not sure how to give multiple search patterns in the below line Or any modification to this existing code would help.

$myString = Select-String -Path C:\Temp\File.txt -Pattern "XX"

Edited Code:

$myFile = Get-Content -Path 'C:\file.txt | Out-String    
if (Select-String $myFile -Pattern 'XX|YY' -NotMatch)    
{    
Do something else    
} 

1 Answer 1

1

Select-String accepts a regular expression as a pattern, so you can just use a logical OR to check for all three strings:

if ( Select-String -Path C:\Temp\File.txt -Pattern 'XX|YY|ZZ' ) {
  echo "yes"
  # Do something else
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi arco444, I'm trying to store the contents of the file.txt like below and using search-string to check if YY or XX is not matching with the text file, then do something, but it throws an error. Am i missing any? $myFile = Get-Content -Path 'C:\file.txt | Out-String if (Select-String $myFile -Pattern 'XX|YY' -NotMatch) { # Do something else }
Firstly, I don't understand what you're trying to do. Secondly, add this code to your original post. Third, we need the error you're running into.
FoxDeploy I'm trying to check whether my file 'file.txt' doesn't contain 'XX' or ''YY'. If it doesn't contain the 'XX' or 'YY' then i'm doing something. Can we use Select-string like above (edited code)? I was getting an error like "A positional parameter cannot be found that accepts argument 'Get-Content'"
Just use the code that @arco444 provided and negate the test clause of the if.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.