问题描述
我正在尝试使用 Powershell 7 过滤 git 中已更改文件的列表。我只想要以“包”或“数据库”开头的文件路径。当我运行代码时,结果没有被过滤并返回所有内容。我如何让过滤工作?我是 Powershell 脚本的新手。
这是我的代码:
https://localhost/productNumber.pdf
解决方法
这里需要注意的几件事:
-contains
是一个 集合包含运算符 - 对于字符串,您需要使用 -like
通配符比较运算符:
$_ -like "*packages*"
或 -match
正则表达式运算符:
$_ -match 'package'
这里要注意的另一件事是 -or
运算符 - 它只需要 boolean 操作数 ($true
/$false
),如果您通过如果需要,它会将操作数转换为 [bool]
。
这意味着以下类型的声明:
$(<# any expression,really #>) -or 'non-empty string'
始终返回 $true
- 因为非空字符串在转换为 $true
时计算结果为 [bool]
。
相反,您需要更改两个单独的比较:
$_ -like '*packages*' -or $_ -like '*database*'
或者,您可以使用 -match
运算符 once,通过使用交替 (|
):
$_ -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'
}