这里有几点需要注意:
-contains
是一个集合包含运算符- 对于字符串,您需要-like
通配符比较运算符:
$_ -like "*packages*"
或-match
正则表达式运算符:
$_ -match 'package'
这里要注意的另一件事是-or
运算符 - 它只需要布尔操作数($true
/ $false
),如果你传递其他任何东西,它会在必要时将操作数转换为。[bool]
这意味着以下类型的语句:
$(<# any expression, really #>) -or 'non-empty string'
总是返回$true
- 因为非空字符串$true
在转换为[bool]
.
相反,您需要更改两个单独的比较:
$_ -like '*packages*' -or $_ -like '*database*'
或者,您可以通过使用交替 ( ) 来使用-match
运算符一次|
:
$_ -match 'package|database'
最后得到类似的东西:
$editedFiles | ForEach-Object {
$sepIndex = $_.IndexOf('/')
if($sepIndex -gt 0 -and $_ -match 'package|database') {
Write-Output $_
}
}
如果过滤是您打算在ForEach-Object
块中执行的全部操作,那么您不妨使用Where-Object
- 它正是为此而设计的 :)
$editedFiles | Where-Object {
$_.IndexOf('/') -gt 0 -and $_ -match 'package|database'
}