How to check if a string contains one of several substrings?

I want to know if a string contains one of abc , def , xyz , etc. I could do it like this:

 $a.Contains("abc") -or $a.Contains("def") -or $a.Contains("xyz") 

Well, this works, but I need to change the code if this list of tweaks changes, and the performance is poor because $a scanned several times.

Is there a more efficient way to do this with a single function call?

+5
source share
2 answers

You can use the -match method and automatically create a regular expression using string.join:

 $referenz = @('abc', 'def', 'xyz') $referenzRegex = [string]::Join('|', $referenz) # create the regex 

Using:

 "any string containing abc" -match $referenzRegex # true "any non matching string" -match $referenzRegex #false 
+8
source

Regex it: $ a -match / \ a | def | xyz | abc / g ( https://regex101.com/r/xV6aS5/1 )

  • Match exact characters in the source string: 'Ziggy stardust' -match 'iggy'

source: http://ss64.com/ps/syntax-regex.html

+2
source

All Articles