Use Select-String to find desired string in a string

Viewed 65

I am trying to find all the strings I define in -Pattern in order. For example,

$string = "My car is Yellow but my car seat is White. I ate Yellow Banana, Yellow lemon and White peach."

Select-String -inputObject $string -Pattern 'Yellow', 'White'

I want the result to be like this in an array object in the order it finds in the string:
Yellow
White
Yellow
Yellow
White
2 Answers

You can use the -AllMatches parameter, however it doesn't look like it will utilize both patterns in this case. Adjusting the pattern might help.

($string | Select-String -AllMatches -Pattern 'Yellow|White').Matches.Value

You can see the matches property in list view, instead of the default custom view. You also need -allmatches. Oh, it didn't come up with white.

$string | Select-String -Pattern Yellow, White -AllMatches | format-list

IgnoreCase : True
LineNumber : 1
Line       : My car is Yellow but my car seat is White. I ate Yellow Banana, Yellow lemon and White peach.
Filename   : InputStream
Path       : InputStream
Pattern    : Yellow
Context    :
Matches    : {0, 0, 0}


Select-String -inputobject $string -Pattern Yellow, White -AllMatches | 
  % matches

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 10
Length   : 6
Value    : Yellow

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 49
Length   : 6
Value    : Yellow

Groups   : {0}
Success  : True
Name     : 0
Captures : {0}
Index    : 64
Length   : 6
Value    : Yellow
Related