PowerShell 中 –Match、-Like 和 –Contains 运算符的区别是什么?


上述三个运算符(Match、Like 和 Contains)都是 PowerShell 中的比较运算符。**Match** 和 **Like** 运算符几乎相似,唯一的区别在于通配符,而 **Contains** 运算符则完全不同。我们将通过示例了解它们的工作方式。

示例

PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "PowerShell"
True
PS C:\WINDOWS\system32> "This is a PowerShell String" -Like "PowerShell"
False
PS C:\WINDOWS\system32> "This is a PowerShell String" -Contains "PowerShell"
False

如果您查看上述示例的输出,则只有 Match 语句的结果为 True,原因是当您在字符串中匹配关键字时,它会检查关键字是否存在。您使用的关键字是单个关键字还是连接词并不重要。下面的语句也为真。

PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "Shell"
True

但通配符 (*) 对 Match 运算符没有帮助。

PS C:\WINDOWS\system32> "This is a PowerShell String" -Match "*PowerShell*"
parsing "*PowerShell*" - Quantifier {x,y} following nothing.
At line:1 char:1
+ "This is a PowerShell String" -Match "*PowerShell*"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException

因此,**Match** 条件不评估正则表达式运算符。相反,Like 运算符与通配符 (*) 一起使用。

PS C:\WINDOWS\system32> "This is a PowerShell String" -like "*PowerShell*"
True

因此,通配符在 Match 和 Like 运算符之间起着重要作用。我们可以检查 **Contains** 运算符是否使用了通配符 (*)。

PS C:\WINDOWS\system32> "This is a PowerShell String" -contains "*PowerShell*"
False

**Contains** 运算符也不适用于通配符 (*) 字符。它与 **Match** 和 **Like** 完全不同,并且适用于**对象集合(数组)**。

PS C:\WINDOWS\system32> "Apple","Dog","Carrot","Cat" -contains "dog"
True

更新于:2020年5月15日

7000+ 次浏览

开启你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.