0

我正在尝试使用 Powershell 7 过滤 git 中已更改文件的列表。我只想要以“包”或“数据库”开头的文件路径。当我运行代码时,不会过滤结果并返回所有内容。我将如何使过滤工作?我是 Powershell 脚本的新手。

这是我的代码:

$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 $_      
    }
}
4

1 回答 1

2

这里有几点需要注意:

-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'
}
于 2020-12-29T18:12:24.250 回答