2017-09-04 91 views
2

我正在尝试编写一个PowerShell脚本,它将一个字符串替换为另一个字符串,并放在单词文件中。我需要更新超过500个字的模板和文件,所以我不想亲手制作。一个问题是,我无法在页脚或页眉中找到文本,因为它们都是单独的,并且是带有图像的表格。我设法找到正常的“正文”文本中的文本,但现在还没有取代它。这是我寻找的代码。在Word文件中替换页眉,页脚和普通文本中的特定文本

$path = "C:\Users\BambergerSv\Desktop\PS\Vorlagen" 
$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 

回答

2

我在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:\Users\Ali\Desktop\Test" -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() 
相关问题