使用Powershell在Word Doc的标题中的文本框中查找和替换

时间:2017-01-07 16:05:05

标签: powershell ms-word powershell-v3.0

我正在尝试使用Powershell来查找和替换Word文档(.docx)标题内的文本框中的某些文本。我能够让它在Header之外的文本中工作但不在内部。我认为它失败了,因为我没有正确访问文本框的内容,所以我添加到最后一行(退出并保存之前)以查看文本是什么但是它打印出来为我的三个项目中的每一个都是空白的头。这是我第一次使用Powershell,我想我可能花了更多的时间来学习和编写它,而不是使用它来节省...

脚本的相关片段如下:

$word = New-Object -COM "Word.Application";
$word.Visible = $false;
$doc = $word.Documents.Open($FullPath);
$selection = $word.Selection;
$section = $doc.sections.item(1);
$header = $section.headers.Item(3);
$FindText = "Cnnn";
$MatchCase = $False;
$MatchWholeWord = $False;
$MatchWildcards = $False;
$MatchSoundsLike = $False;
$MatchAllWordForms = $False;
$Forward = $True;
$wdFindContinue = 1;
$Wrap = $wdFindContinue;
$Format = $False;
$wdReplaceNone = 0;
$ReplaceAll = 2;
$ReplaceWith = "C" + $newString; 
$a = $header.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ` 
$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,` 
$Wrap,$Format,$ReplaceWith, $ReplaceAll);

Write-Host ("Header is: " + $header.Text);

$doc.Save();
$word.Quit();

1 个答案:

答案 0 :(得分:0)

您需要将搜索结果应用于.TextFrame.TextRange.Find或任何包含TextBox文字的shape对象。 你可以尝试这样的事情:

If ($header.ShapeRange.Count) {
  ForEach ($shp in $header.ShapeRange) {
    If ($shp.TextFrame.HasText) {
      $obj = $shp.TextFrame.TextRange.Find
      $a = $obj.Execute($FindText,$MatchCase,$MatchWholeWord,` 
             $MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,` 
             $Wrap,$Format,$ReplaceWith,$ReplaceAll)
    }
  }
}