PowerShell:查找文本文件中的单词是否是字符串数组的一部分

PowerShell: Finding if a word in a text file is part of an array of strings

我有一个包含一堆 .txt 文件的文件夹。我想遍历它们并检查它们是否包含存储在字符串数组中的关键字。如果找到匹配项,我想将该文件存储在以匹配项命名的新文件夹中。例如,我正在检查我的一个文本文件中是否有“OVERTIME”这个词;如果找到匹配项,我想将文件保存在名为“OVERTIME”的新文件夹中。我打算使用 move-item 将文件从当前文件夹移动到新文件夹,这样文件就会从旧文件夹中删除。以下是我的初始代码;我不确定如何设置嵌套循环以及如何检查是否匹配。

$reports_name = @('MYTIME','NOTIME','OVERTIME')
Get-ChildItem "C:\Users\My_User\Desktop\test" -Filter *.txt | 
Foreach-Object {
$content = Get-Content $_.FullName
foreach($line in $content) {
if($line -in $reports_name){
    move-item $content -Destination C:\Users\My_User\Desktop$line
}
}
$reports_name = 'MYTIME', 'NOTIME', 'OVERTIME'

Select-String -List $reports_name 'C:\Users\My_User\Desktop\test\*.txt' |
  Move-Item -LiteralPath { $_.Path } `
            -Destination { "C:\Users\My_User\Desktop$($_.Pattern)" } -WhatIf

注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf

  • Select-String-List 开关仅查找每个输入文件中的 first 匹配项。

    • 注意:Select-String 默认将其(隐含的)-Pattern 参数解释为 正则表达式 ;添加 -SimpleMatch 开关以将它们视为 文字 ;无论哪种方式,默认情况下匹配都是 case-insensitive;添加 -CaseSensitive 区分大小写匹配。
  • Select-String 在每个输入文件基础上输出的 Move-Item call uses to access the properties of the Microsoft.PowerShell.Commands.MatchInfo 个实例(每个输入文件一个,感谢 -List)。