我从未让-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
Run Code Online (Sandbox Code Playgroud)
该-contains操作不是字符串操作,而是一个收集容器操作:
'a','b','c' -contains 'b' # correct use of -contains against collection
Run Code Online (Sandbox Code Playgroud)
从about_Comparison_Operators帮助主题:
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
Run Code Online (Sandbox Code Playgroud)
通常你会-like在PowerShell中使用字符串运算符,它支持Windows样式的通配符匹配(*任何数量的任何字符,?对于任何[abcdef]一个字符集,对于一个字符集):
'abc' -like '*b*' # $true
'abc' -like 'a*' # $true
Run Code Online (Sandbox Code Playgroud)
另一个选择是-match运营商:
'abc' -match 'b' # $true
'abc' -match '^a' # $true
Run Code Online (Sandbox Code Playgroud)
对于逐字子字符串匹配,您可能希望转义任何输入模式,因为它-match是一个正则表达式运算符:
'abc.e' -match [regex]::Escape('c.e')
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用该String.Contains()方法:
'abc'.Contains('b') # $true
Run Code Online (Sandbox Code Playgroud)
需要注意的是,与powershell字符串运算符不同,它区分大小写.
String.IndexOf() 是另一种选择,这个允许你覆盖默认的区分大小写:
'ABC'.IndexOf('b', [System.StringComparison]::InvariantCultureIgnoreCase) -ge 0
Run Code Online (Sandbox Code Playgroud)
IndexOf()-1如果未找到子字符串,则返回,因此任何非负返回值都可以解释为已找到子字符串.
| 归档时间: |
|
| 查看次数: |
3699 次 |
| 最近记录: |