在Word文件中替换标题,页脚和普通文本中的特定文本



我正在尝试编写一个powershell脚本,该脚本将一个字符串替换为Word文件中的另一个字符串。我需要更新500多个单词模板和文件,以便我不想手工制作。一个问题是我找不到页脚或标题,因为它们都是个体,并且是带有图像的表。我设法在普通的"正文"文本中找到文本,但现在还没有替换。这是我查找的代码。

$path = "C:UsersBambergerSvDesktopPSVorlagen"
$files = Get-Childitem $path -Include *dotm, *docx, *.dot, *.doc, *.DOT, *DOTM, *.DOCX, *.DOC -Recurse |
         Where-Object { !($_.PSIsContainer) }
$application = New-Object -ComObject Word.Application
$application.Visible = $true
$findtext = "www.subdomain.domain.com"
function getStringMatch {
    foreach ($file In $files) {
        #Write-Host $file.FullName
        $document = $application.Documents.Open($file.FullName, $false, $true)
        if ($document.Content.Text -match $findtext) {
            Write-Host "found text in file " $file.FullName "`n"
        }
        try {
            $application.Documents.Close()
        } catch {
            continue
            Write-Host $file.FullName "is a read only file" #if it is write protected because of the makros
        }
    }
    $application.Quit()
}
getStringMatch

我在Internet上搜索。我找到了这个问题的答案。

首先,您需要了解VBA。在MS Word中写下以下宏,然后保存。

Public Function CustomReplace(findValue As String, replaceValue As String) As String
 For Each myStoryRange In ActiveDocument.StoryRanges
     myStoryRange.find.Execute FindText:=findValue, Forward:=True, ReplaceWith:=replaceValue, replace:=wdReplaceAll
     While myStoryRange.find.Found
           myStoryRange.find.Execute FindText:=findValue, Forward:=True, ReplaceWith:=replaceValue, replace:=wdReplaceAll
     Wend
     While Not (myStoryRange.NextStoryRange Is Nothing)
          Set myStoryRange = myStoryRange.NextStoryRange
          myStoryRange.find.Execute FindText:=findValue, Forward:=True, ReplaceWith:=replaceValue, replace:=wdReplaceAll
          While myStoryRange.find.Found
               myStoryRange.find.Execute FindText:=findValue, Forward:=True,ReplaceWith:=replaceValue, replace:=wdReplaceAll
          Wend
     Wend
  Next myStoryRange
CustomReplace = ActiveDocument.FullName
End Function

上述宏添加到MS Word之后,转到PowerShell并执行以下代码。

$word = New-Object -ComObject Word.Application
$word.visible=$false
$files = Get-ChildItem "C:UsersAliDesktopTest" -Filter *.docx
$find=[ref]"Hello"
$replace=[ref]"Hi"

for ($i=0; $i -lt $files.Count; $i++) {
  $filename = $files[$i].FullName 
  $doc = $word.Documents.Open($filename)
  $word.Run("CustomReplace",$find,$replace)
  $doc.Save()
  $doc.close()
  }
 $word.quit()

最新更新