【问题标题】:How can I modify this PowerShell script to continue looking for one string after another?如何修改此 PowerShell 脚本以继续查找一个又一个字符串?
【发布时间】:2020-02-11 07:15:10
【问题描述】:

我希望这个 power shell 脚本一个接一个地搜索多个字符串的出现,并将结果附加到 .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_String”,我希望能够指定“Second_String”、“Third_String”等,而不是每次都替换 First_String。

【问题讨论】:

标签: string powershell file search find


【解决方案1】:

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

将文档的上下文读取为字符串$text = $document.content.text,然后使用Select-String $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()
}

请注意,如果您尝试查找具有保留正则表达式字符的字符串,您需要先将它们转义

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 2021-08-15
    • 2011-01-01
    • 2021-06-03
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多