首页 > 解决方案 > 使用 Select-String 在字符串中查找所需的字符串

问题描述

我正在尝试按顺序查找我在 -Pattern 中定义的所有字符串。例如,

$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

标签: powershell

解决方案


您可以使用该-AllMatches参数,但在这种情况下它看起来不会同时使用这两种模式。调整模式可能会有所帮助。

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

推荐阅读