在 PowerShell 中使用 txt 文件作为列表 array/variable

Use txt file as list in PowerShell array/variable

我有一个搜索字符串的脚本(在本例中为 "End program")。然后它遍历文件夹中的每个文件并输出不包含该字符串的任何文件。

当短语被硬编码时,它工作得很好,但我想通过创建一个文本文件来保存字符串来使其更加动态。将来,我希望能够添加到文本文件中的字符串列表中。我无法在任何地方在线找到此内容,因此不胜感激。

当前代码:

$Folder = "\test path"
$Files = Get-ChildItem $Folder -Filter "*.log" |
         ? {$_.LastWriteTime -gt (Get-Date).AddDays(-31)} 

# String to search for within the file
$SearchTerm = "*End program*"

foreach ($File in $Files) {
    $Text = Get-Content "$Folder$File" | select -Last 1

    if ($Text | WHERE {$Text -inotlike $SearchTerm}) {
        $Arr += $File
    }
}
if ($Arr.Count -eq 0) {
   break
}

这是代码的简化版本,仅显示有问题的区域。我想将 "End program" 和另一个字符串 "End" 放入文本文件中。

文件内容如下:

*End program*,*Start*

如果您想检查一个文件是否包含(或不包含)一些给定的术语,您最好使用正则表达式。从文件中读取术语,转义它们,并将它们加入 alternation:

$terms = Get-Content 'C:\path\to\terms.txt' |
         ForEach-Object { [regex]::Escape($_) }

$pattern = $terms -join '|'

文件中的每个术语都应该在单独的行中,并且没有前导或尾随通配符。像这样:

End program
Start

有了它,您可以检查文件夹中的文件是否不包含任何这样的术语:

Get-ChildItem $folder | Where-Object {
    -not $_.PSIsContainer -and
    (Get-Content $_.FullName | Select-Object -Last 1) -notmatch $pattern
}

如果您想检查整个文件而不是只检查最后一行更改

Get-Content $_.FullName | Select-Object -Last 1

Get-Content $_.FullName | Out-String