foreach 关键字后缺少开头

Missing opening after foreach keyword

我的 foreach 循环有问题。我正在尝试打印文件中不存在的字符串。代码片段在 foreach 循环中抛出错误,指出在 foreach keyword.How 之后缺少开口 '(' 以克服此错误。

要查找的字符串为文件abc.txt中的'nature','kite','venue','street','venture'.

我有以下代码片段

$Pattern = @('nature|kite|venue|street|venture')
$Test = (Get-Content -Path .\file.txt | Select-String -Pattern $Pattern -AllMatches)
$Test = foreach {$_.matches.Value}
$t = $Pattern -split('\|')|where{$Test -notcontains $_}
$Test = (Get-Content -Path .\file.txt | Select-String -Pattern $Pattern -AllMatches) | foreach {$_.matches.Value}
foreach ($t in $Test) {
    $Pattern -split('\|')|where{$Test -notcontains $_}
}

我会走不同的路:

  • 有一个字符串数组,
  • 通过将它们与 |
  • 连接起来构建一个正则表达式
  • Sort-Object -UniqueSelect-String 个结果

## Q:\Test19\SO_56488287.ps1
$strings = @('nature','kite','venue','street','venture')
$Pattern = [RegEx]($strings -join '|')
$file    = '.\file.txt'

$Found = (Get-Content -Path $file |
          Select-String -Pattern $Pattern -AllMatches
         ).Matches.Value | Sort-Object -Unique

$Missing = $Strings | Where {$Found -notcontains $_}

if($Missing){
    "Strings missing in $file"
    $Missing
} else {
    "All strings present in $file"
}