PowerShell 包含操作符

PowerShell 包含操作符

在 PowerShell 中有不同的运算符可用于过滤/比较或查找与指定输入字符串匹配的元素。-contains 是主要的比较运算符之一,归类为包含类型运算符。

有四个主要的包含类型运算符。

  • -contains
  • -notcontains
  • -in
  • -notin

在本文中,我们只关注 -contains 运算符。此运算符如果有匹配项,始终返回布尔值(true/false)。此外,性能方面,-contains 运算符返回结果的速度相当快,因为它一找到第一个匹配项就停止比较输入。

PowerShell 中的 -contains 运算符

该运算符可用于检查集合中是否包含特定元素。其语法如下。

[set / collection] -contains [test-value or test-object]

[set/collection] 可以是一组字符串值(用逗号分隔),例如 "Hello""FOX", "2ndLane"

[test-value or test-object] 可以是一个元素或一组元素(集合),例如 "Hello""Hello", "FOX", "No2"

检查某个特定元素

  • 示例 01:
"Hello", "FOX", "2ndLane" -contains "2ndLane"

输出:

True

输入元素/值为 "2ndLane",它可以在左侧的集合/集合中找到。因此,输出/结果显然为 True

  • 示例 02:
"Hello", "FOX", "2ndLane" -contains "NotInTheCollection"

输出:

False

输入元素/值为 "NotInTheCollection",它不包括在右侧的集合中。因此,上面的命令被评估为 False

关于 -contains 运算符的一个重要事实是,它在给定的集合/集合中检查确切的输入元素。当作为输入元素给定部分/子字符串时,该命令将被评估为 False

  • 示例 03:
"Hello", "FOX", "FullStringGiven" -contains "StringGiven"

输出:

False

在上面的示例中,输入元素是 "StringGiven",但它是右侧集合中 "FullStringGiven" 元素的子字符串。因此,输入元素与右侧集合中的确切元素不匹配,结果如预期为 False

使用 PowerShell 中的 -contains 运算符检查一组元素/集合

-contains 运算符的一个最大优点是它可以用于查找给定的集合/集合是否与输入集合匹配。需要记住的是,该运算符检查左侧(给定集合)和右侧(输入集合/测试集合)是否存在相同的实例。这意味着这些包含运算符在输入对象(测试对象)是集合时使用引用相等。

示例 01

$leftsideobj = "Hello", "NewString1"

在这里,我们将 $leftsideobj 变量分配给元素集合(集合)。

$leftsideobj, "AnotherString" -contains $leftsideobj

然后,我们使用 -contains 运算符查找匹配项。

输出:

True

该命令被评估为 True。因为输入集合是 $leftsideobj,并且同一实例在左侧集合中可用。意味着引用相等已满足。因此,结果为 True

示例 02

$newleftsideobj = "Hello", "Test"

在这里,我们将 $newleftsideobj 变量分配给包含 "Hello""Test" 元素的集合。

`"Hello", "Test", "NewString1" -contains $newleftsideobj`

输出:

False

上述命令被评估为 False。你可以看到,输入集合(右侧)是 $newleftsideobj,间接包含两个元素 "Hello""Test"。如果你注意左侧,我们得到了可用的 "Hello""Test" 元素。但是它不满足引用相等。这就是为什么输出为 False

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

相关文章 - PowerShell Operator