PowerShell 和 -contains 运算符 [英] PowerShell and the -contains operator

查看:26
本文介绍了PowerShell 和 -contains 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下片段:

"12-18" -Contains "-"

您会认为这会被评估为 true,但事实并非如此.这将评估为 false 代替.我不确定为什么会发生这种情况,但确实如此.

You’d think this evaluates to true, but it doesn't. This will evaluate to false instead. I’m not sure why this happens, but it does.

为了避免这种情况,您可以改用它:

To avoid this, you can use this instead:

"12-18".Contains("-")

现在表达式的计算结果为真.

Now the expression will evaluate to true.

为什么第一个代码片段会这样?- 有什么特别之处不能很好地与 -Contains 配合使用吗?文档没有提及任何相关内容.

Why does the first code snippet behave like that? Is there something special about - that doesn't play nicely with -Contains? The documentation doesn't mention anything about it.

推荐答案

-Contains 运算符不进行子字符串比较,匹配必须在完整字符串上,用于搜索集合.

The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

来自您链接到的文档:

-包含描述:收容操作员.说明参考值集合是否包含单个测试值.

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

在您提供的示例中,您正在处理一个仅包含一个字符串项的集合.

In the example you provided you're working with a collection containing just one string item.

如果您阅读链接到的文档,您将看到一个演示此行为的示例:

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

示例:

PS C:> "abc", "def" -Contains "def"
True

PS C:> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

我认为您想要的是 -Match 运算符:

I think what you want is the -Match operator:

"12-18" -Match "-"

返回True.

重要提示:正如评论和链接文档,需要注意的是-Match操作符使用正则表达式以执行文本匹配.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.

这篇关于PowerShell 和 -contains 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆