【问题标题】:Powershell Return the highest 4 Digit Number Found in a String Pattern - Search Word DocumentsPowershell 返回字符串模式中找到的最高 4 位数字 - 搜索 Word 文档
【发布时间】:2016-03-15 22:02:25
【问题描述】:

我正在尝试在一组文档中返回在字符串模式中找到的 最高 4 位数字。

字符串模式:3 个字母破折号 4 个数字

word 文档中包含一个文档标识符代码,如下所示。

示例文件:

汽车零件.docx > CPW - 2345

CarHandles.docx > CPW - 8723

CarList.docx > CPA - 9083

我已经引用了我正在尝试调整的示例代码。我不是 VBA 或 powershell 程序员 - 所以我尝试做的事情可能是错误的?

我很高兴看到替代方案 - 在 Windows 平台上。

我已经参考了这个来帮助我开始

http://chris-nullpayload.rhcloud.com/2012/07/find-and-replace-string-in-all-docx-files-recursively/

PowerShell: return the number of instances find in a file for a search pattern

Powershell: return filename with highest number

$list = gci "C:\Users\WP\Desktop\SearchFiles" -Include *.docx -Force -recurse
foreach ($foo in $list) {

$objWord = New-Object -ComObject word.application
$objWord.Visible = $False

$objDoc = $objWord.Documents.Open("$foo")
$objSelection = $objWord.Selection 

$Pat1 = [regex]'[A-Z]{3}-[0-9]{4}'   # Find the regex match 3 letters  followed by 4 numbers eg     HGW - 1024

$findtext= "$Pat1"

 $highestNumber = 

 # Find the highest occurrence of this pattern found in the documents searched - output to text file or on screen

Sort-Object |                   # This may also be wrong -I added it for when I find the pattern
Select-Object -Last 1 -ExpandProperty Name


<#   The below may not be needed  - ?

$ReplaceText = ""

$ReplaceAll = 2
$FindContinue = 1
$MatchFuzzy = $False
$MatchCase = $False
$MatchPhrase = $false
$MatchWholeWord = $True
$MatchWildcards = $True
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False

$objSelection.Find.execute(
    $FindText,
    $MatchCase,
    $MatchWholeWord,
    $MatchWildcards,
    $MatchSoundsLike,
    $MatchAllWordForms,
    $Forward,
    $Wrap,
    $Format,
    $ReplaceText,
    $ReplaceAll
  }

}
#>

感谢任何关于如何进行的建议 -

【问题讨论】:

  • 最好的方法是确定究竟是什么不工作,找出原因然后解决它。如果您在启动和运行它时遇到任何特定问题,请随时提出。
  • 嗨 Andrew,我找不到 $Pat1 = [regex]'[A-Z]{3}-[0-9]{4}' 开头的模式 - 我已在其中添加注释我被困在代码上。
  • 顺便说一句,您使用的是哪个 Powershell 版本?
  • 嗨 Andrew,我相信 5,我在 Windows 10 上 - 我也有电源外壳 ISE。谢谢

标签: regex powershell ms-word


【解决方案1】:

试试这个:

# This library is needed to extact zip archives. A .docx is a zip archive
# .NET 4.5 or later is requried
Add-Type -AssemblyName System.IO.Compression.FileSystem

# This function gets plain text from a word document
# adapted from http://stackoverflow.com/a/19503654/284111
# It is not ideal, but good enough
function Extract-Text([string]$fileName) {

  #Generate random temporary file name for text extaction from .docx
  $tempFileName = [Guid]::NewGuid().Guid

  #Extract document xml into a variable ($text)
  $entry = [System.IO.Compression.ZipFile]::OpenRead($fileName).GetEntry("word/document.xml")
  [System.IO.Compression.ZipFileExtensions]::ExtractToFile($entry,$tempFileName)
  $text = [System.IO.File]::ReadAllText($tempFileName)
  Remove-Item $tempFileName

  #Remove actual xml tags and leave the text behind
  $text = $text -replace '</w:r></w:p></w:tc><w:tc>', " "
  $text = $text -replace '</w:r></w:p>', "`r`n"
  $text = $text -replace "<[^>]*>",""

  return $text
}

$fileList = Get-ChildItem "C:\Users\WP\Desktop\SearchFiles" -Include *.docx -Force -recurse
# Adapted from http://stackoverflow.com/a/36023783/284111
$fileList | 
  Foreach-Object {[regex]::matches((Extract-Text $_), '(?<=[A-Za-z]{3}\s*(?:-|–)\s*)\d{4}')} | 
  Select-Object -ExpandProperty captures | 
  Sort-Object value -Descending | 
  Select-Object -First 1 -ExpandProperty value 

这背后的主要思想不是绕开 Word 的 COM api,而是尝试手动从文档中提取文本信息。

【讨论】:

  • 安德鲁,感谢您的慷慨帮助。它确实找到了最高的数字并将其显示在屏幕上。我很高兴-它可以满足我的需要-从文档中找到最高的数字-现在对我来说已经足够了。它确实给出了一些错误,但考虑到我没有经验 - 我将进一步了解这方面并慢慢提高我的技能 - 再次感谢您的帮助。
【解决方案2】:

获得最高数字的方法是首先使用正则表达式将其隔离,然后排序并选择第一项。像这样的:

[regex]::matches($objSelection, '(?<=[A-Z]{3}\s*-\s*)\d{4}')  `
  | Select -ExpandProperty captures `
  | sort value -Descending `
  | Select -First 1 -ExpandProperty value `
  | Add-Content outfile.txt

我认为您在使用正则表达式时遇到的问题是您的示例数据在代码中的破折号周围包含空格,而这些空格在您的模式中是不允许的。

【讨论】:

  • 嗨戴夫-谢谢你的帮助-我已经完成了 $list = gci "C:\Users\WP\Desktop\Search\" -包括 .docx -Force -recurse foreach ($foo in $list) {$objWord = New-Object -ComObjectword.application$objWord.Visible = $False $objDoc = $objWord.Documents.Open("$foo")$objSelection = $objWord.Selection [正则表达式] ::matches($objSelection, '(?)\d{4}') ` |选择 -ExpandProperty 捕获 ` |排序值 - 降序 ` |选择-First 1 -ExpandProperty 值` | Add-Content outfile.txt } - 我一定做错了 -+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
  • 谢谢 Dave - 我将使用你的代码 - 添加到我的 powershell 工具中:)
猜你喜欢
  • 2015-01-25
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2019-10-04
  • 1970-01-01
相关资源
最近更新 更多