2017-09-13 26 views
0

我从来没有-contains操作员在Powershell中工作我不知道为什么。包含操作员不在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 
+0

你”再loo ''匹配'Windows''或'-like'* Windows *'',包含的内容仅用于数组。 – ConnorLSW

+0

的'-match'运营商,据我了解,是正则表达式,其中包含通配符的较小的子集工作,这样也能发挥作用。但是如果我想恰当地使用'contains'运算符,我该如何做?我的问题是不是我*如何做到这一点?*而是*为什么会发生这种从来没有为我工作,我在做什么错这个操作在这里吗?*有100办法做的事。我可以从.NET基类库中调用'“字符串值”.Contains()'。 –

+0

[PowerShell和的-contains运算符(https://stackoverflow.com/questions/18877580/powershell-and-the-contains-operator) –

回答

6

-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 

通常你会使用-like串操作者在PowerShell,该支持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如果没有找到子串,所以任何非负的返回值可以被解释为找到了子字符串。

+0

阿的可能的复制!正如我怀疑的。你的第一行回答了我的问题。谢谢。我应该花点时间仔细阅读文档。 –

+0

@ WaterCoolerv2有很多的好东西在'about_ *'帮助主题,我更新了遏制经营者从'about_Comparison_Operators'文件 –

+0

这是正确的表格答案。我知道他们,@Mathias。只是还没有时间仔细阅读全部内容。 –

2

'-contains'操作符最适合与列表或数组进行比较,例如,

$list = @("server1","server2","server3") 
if ($list -contains "server2"){"True"} 
else {"False"} 

输出:

True 

我建议使用 '-match',而不是字符串比较:

$str = "windows" 
if ($str -match "win") {"`$str contains 'win'"} 
if ($str -match "^win") {"`$str starts with 'win'"} 
if ($str -match "win$") {"`$str ends with 'win'"} else {"`$str does not end with 'win'"} 
if ($str -match "ows$") {"`$str ends with 'ows'"} 

输出:

$str contains 'win' 
$str starts with 'win' 
$str does not end with 'win' 
$str ends with 'ows'