2017-09-04 93 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() 
相關問題