严格来说string -match ... 和collection -match ... 是两个不同的运算符。
第一个获取一个布尔值并填充$matches。
第二个获取与模式匹配的每个集合项,显然没有填充$matches。
如果文件包含一行(第一个运算符有效),您的示例应该可以按预期工作。
如果文件包含 2+ 行,则使用第二个运算符并且不设置 $matches。
应用于集合的其他布尔运算符也是如此。
即collection -op ... 返回item -op ... 为真的项目。
例子:
1..10 -gt 5 # 6 7 8 9 10
'apple', 'banana', 'orange' -match 'e' # apple, orange
如果使用得当,应用于集合的布尔运算符会很方便。
但它们也可能会令人困惑并导致容易犯错误:
$object = @(1, $null, 2, $null)
# "not safe" comparison with $null, perhaps a mistake
if ($object -eq $null) {
'-eq gets @($null, $null) which is evaluated to $true by if!'
}
# safe comparison with $null
if ($null -eq $object) {
'this is not called'
}
-match 和 -notmatch 的另一个示例可能看起来令人困惑:
$object = 'apple', 'banana', 'orange'
if ($object -match 'e') {
'this is called'
}
if ($object -notmatch 'e') {
'this is also called, because "banana" is evaluated to $true by if!'
}