PowerShell and the -contains operator
考虑以下代码段:
1 | "12-18" -Contains"-" |
您可能以为这是
为了避免这种情况,您可以改用以下方法:
1 | "12-18".Contains("-") |
现在,表达式将评估为true。
为什么第一个代码段的行为如此?
从您链接到的文档中:
-Contains
Description: Containment operator. Tells whether a collection of reference values includes a single test value.
在您提供的示例中,您正在使用仅包含一个字符串项的集合。
如果您阅读链接到的文档,您将看到一个示例来演示此行为:
例子:
1 2 3 4 5 | PS C:\>"abc","def" -Contains"def" True PS C:\>"Windows","PowerShell" -Contains"Shell" False #Not an exact match |
我认为您想要的是
1 | "12-18" -Match"-" |
返回
重要说明:正如注释和链接文档中指出的那样,应注意
您可以使用
1 | "12-18" -like"*-*" |
或
1 | "12-18" -split"" -contains"-" |
-
like 是最好的,或者至少是最简单的。 -
match 用于正则表达式比较。
参考:https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6