String 如何修改此PowerShell脚本以继续查找一个又一个字符串?

String 如何修改此PowerShell脚本以继续查找一个又一个字符串?,string,powershell,file,search,find,String,Powershell,File,Search,Find,我希望这个powershell脚本能够搜索出现的多个字符串,一个接一个,并将结果附加到一个.txt文件中 目前,我正在指定要查找的字符串,等待脚本完成该字符串的查找并将结果传输到电子表格中。这需要花费很多时间,因为我必须不断指定要查找的字符串,特别是因为我需要查找的字符串远远超过100个 #ERROR REPORTING ALL Set-StrictMode -Version latest $path = "C:\Users\username\Documents\FileName" $files

我希望这个powershell脚本能够搜索出现的多个字符串,一个接一个,并将结果附加到一个.txt文件中

目前,我正在指定要查找的字符串,等待脚本完成该字符串的查找并将结果传输到电子表格中。这需要花费很多时间,因为我必须不断指定要查找的字符串,特别是因为我需要查找的字符串远远超过100个

#ERROR REPORTING ALL
Set-StrictMode -Version latest
$path = "C:\Users\username\Documents\FileName"
$files = Get-Childitem $path -Include *.docx,*.doc,*.ppt, *.xls, 
*.xlsx, *.pptx, *.eap -Recurse | Where-Object { !($_.psiscontainer) }
$output = 
"C:\Users\username\Documents\FileName\wordfiletry.txt"
$application = New-Object -comobject word.application
$application.visible = $False
$findtext = "First_String"

Function getStringMatch
{
  # Loop through all *.doc files in the $path directory
  Foreach ($file In $files)
  {
   $document = $application.documents.open($file.FullName,$false,$true)
   $range = $document.content
   $wordFound = $range.find.execute($findText)

   if($wordFound) 
    { 
     "$file.fullname has found the string called  $findText and it is 
$wordfound" | Out-File $output -Append
    }

  }
$document.close()
$application.quit()
}

getStringMatch

此脚本将成功查找“First\u String”,我希望能够指定“Second\u String”、“Third\u String”等,而不是每次都替换第一个字符串。

作为@Mathias建议的替代方法,您可以使用正则表达式来查询文档文本

将文档的上下文作为字符串读取
$text=$document.content.text
,然后使用
选择字符串$findtext-AllMatches
$findtext
作为正则表达式的字符串表示来计算匹配项

例如:

# pipe delimited string as a regular expression
$findtext = "First_String|Second_String|Third_String"

Function getStringMatch
{
  # Loop through all *.doc files in the $path directory
  Foreach ($file In $files)
  {
    $document = $application.documents.open($file.FullName,$false,$true)
    $text = $document.content.text
    $result = $text | Select-String $findtext -AllMatches

    if($result) 
    {
      "$file.fullname has found the strings called $($result.Matches.Value) at indexes $($result.Matches.Index)" | Out-File $output -Append
    }
  }

  $document.close()
  $application.quit()
}
请注意,如果您试图查找具有保留正则表达式字符的字符串,则需要首先对其进行转义