powershell - 包含不在 Powershell 中工作的运算符

标签 powershell

我从来没有让 -contains 运算符在 Powershell 中工作,我不知道为什么。

这是它不起作用的示例。我使用 -like 代替它,但如果你能告诉我为什么它不起作用,我会很高兴。

PS HKLM:\Software\Microsoft\Windows NT\CurrentVersion> (gp . P*).ProductName
Windows 10 Enterprise

PS HKLM:\Software\Microsoft\Windows NT\CurrentVersion> (gp . P*).ProductName -contains "Windows"
False

PS HKLM:\Software\Microsoft\Windows NT\CurrentVersion> (gp . P*).ProductName | gm | select TypeName | Get-Unique

TypeName     
--------     
System.String

最佳答案

-contains 运算符不是字符串运算符,而是集合包含 运算符:

'a','b','c' -contains 'b' # correct use of -contains against collection

来自about_Comparison_Operators help topic :

Type         Operator      Description
Containment  -contains     Returns true when reference value contained in a collection
             -notcontains  Returns true when reference value not contained in a collection
             -in           Returns true when test value contained in a collection
             -notin        Returns true when test value not contained in a collection

通常您会在 PowerShell 中使用 -like 字符串运算符,它支持 Windows 风格的通配符匹配(* 用于任意数量的任意字符,? 恰好是任何字符之一,[abcdef] 是字符集之一):

'abc' -like '*b*' # $true
'abc' -like 'a*' # $true

另一种选择是 -match 运算符:

'abc' -match 'b' # $true
'abc' -match '^a' # $true

对于逐字子串匹配,您可能希望转义任何输入模式,因为 -match 是一个正则表达式运算符:

'abc.e' -match [regex]::Escape('c.e')

另一种方法是使用 String.Contains()方法:

'abc'.Contains('b') # $true

需要注意的是,与 powershell 字符串运算符不同,它区分大小写。


String.IndexOf()是另一种选择,这个允许您覆盖默认的区分大小写:

'ABC'.IndexOf('b', [System.StringComparison]::InvariantCultureIgnoreCase) -ge 0

IndexOf() 如果未找到子字符串,则返回 -1,因此任何非负返回值都可以解释为已找到子字符串。

关于powershell - 包含不在 Powershell 中工作的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46194946/

相关文章:

powershell - Powershell 中不同的文件类型列表

powershell - 通过动态变量名获取变量

powershell - powershell 命令周围的括号与没有的有什么不同?

c# - 在应用程序内操作 PowerShell?

powershell - Windows Server 2008 R2 PowerShell和Internet Explorer 9

java - 未知生命周期阶段 ".mainClass=com.blobs.quickstart.App"

powershell - 如何使用 Powershell 脚本将 csv 转换为小写

ruby - Powershell ISE utf8 输入与 Ruby 的不同

powershell - 传递给 Invoke-Command 的属性将类型从 IDictionary 更改为 HashTable

azure - 我可以找到 Azure 子网中可用 IP 地址的数量吗?