Powershell中存在多个条件的筛选器Foreach对象结果不工作
我正在尝试使用Powershell 7筛选git中已更改文件的列表。我只需要以“packages”或“database”开头的文件路径。当我运行代码时,结果不会被过滤,所有内容都会返回。我如何让过滤工作?我是Powershell脚本编写新手 这是我的密码:Powershell中存在多个条件的筛选器Foreach对象结果不工作,powershell,powershell-7.0,Powershell,Powershell 7.0,我正在尝试使用Powershell 7筛选git中已更改文件的列表。我只需要以“packages”或“database”开头的文件路径。当我运行代码时,结果不会被过滤,所有内容都会返回。我如何让过滤工作?我是Powershell脚本编写新手 这是我的密码: $editedFiles = git diff HEAD [git commit id] --name-only $editedFiles | ForEach-Object { $sepIndex = $_.IndexOf('/')
$editedFiles = git diff HEAD [git commit id] --name-only
$editedFiles | ForEach-Object {
$sepIndex = $_.IndexOf('/')
if($sepIndex -gt 0 -and ($_ -contains 'packages' -or 'database')) {
Write-Output $_
}
}
这里有几件事需要注意:
-contains
是一个集合包含运算符-对于字符串,您需要类似于-like
的通配符比较运算符:
$_ -like "*packages*"
$_ -match 'package'
或-match
正则表达式运算符:
$_ -like "*packages*"
$_ -match 'package'
这里需要注意的另一件事是-或
运算符-它只接受布尔操作数($true
/$false
),如果您传递其他任何内容,它将在必要时将操作数转换为[bool]
这意味着以下类型的声明:
$(<# any expression, really #>) -or 'non-empty string'
或者,您可以使用一次交替(|
)来使用-match
操作符:
最终得到的结果是:
$editedFiles | ForEach-Object {
$sepIndex = $_.IndexOf('/')
if($sepIndex -gt 0 -and $_ -match 'package|database') {
Write-Output $_
}
}
如果您只想在
ForEach对象
块中进行过滤,那么您最好使用Where Object
——它正是为此而设计的:)
这里有几件事需要注意:
-contains
是一个集合包含运算符-对于字符串,您需要类似于-like
的通配符比较运算符:
$_ -like "*packages*"
$_ -match 'package'
或-match
正则表达式运算符:
$_ -like "*packages*"
$_ -match 'package'
这里需要注意的另一件事是-或
运算符-它只接受布尔操作数($true
/$false
),如果您传递其他任何内容,它将在必要时将操作数转换为[bool]
这意味着以下类型的声明:
$(<# any expression, really #>) -or 'non-empty string'
或者,您可以使用一次交替(|
)来使用-match
操作符:
最终得到的结果是:
$editedFiles | ForEach-Object {
$sepIndex = $_.IndexOf('/')
if($sepIndex -gt 0 -and $_ -match 'package|database') {
Write-Output $_
}
}
如果您只想在
ForEach对象
块中进行过滤,那么您最好使用Where Object
——它正是为此而设计的:)
您的Where对象示例正是我想要的。非常感谢。您的Where对象示例正是我想要的。非常感谢。