我有一个简单的要求。我需要在 Word 文档中搜索一个字符串,因此我需要在文档中获取匹配的行/一些单词。
到目前为止,我可以在包含 Word 文档的文件夹中成功搜索字符串,但它根据是否可以找到搜索字符串返回 True / False。
#ERROR REPORTING ALL
Set-StrictMode -Version latest
$path = "c:\MORLAB"
$files = Get-Childitem $path -Include *.docx,*.doc -Recurse | Where-Object { !($_.psiscontainer) }
$output = "c:\wordfiletry.txt"
$application = New-Object -comobject word.application
$application.visible = $False
$findtext = "CRHPCD01"
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 $wordfound" | Out-File $output -Append …Run Code Online (Sandbox Code Playgroud)