【发布时间】: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