0

Is there a good way to perform an insert of text into the middle of an existing Word document using PowerShell? It appears straightforward to open from a template:

$TemplatePath = "C:\Template.dotx"
$SavePath = "C:\Saved.docx"
$Word = New-Object -ComObject "Word.Application"
$Doc = $Word.Documents.Add( $TemplatePath )
$Selection = $Word.Selection
$Range = $Doc.Content

At that point, it's unclear if we should insert string "tags" and perform a $Selection.Find.Execute() to the tag, or if there's a better way to seek into the document and then write the new content from that point onward. I've tried a few methods, but $Selection.Find.Execute() doesn't insert at the location found, and $Range doesn't have a TypeParagraph() method.

Is there a standardized way to do this?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Matt
  • 1
  • 1
  • 1
  • Are you looking to replace text? Or find a specific phrase, and insert text before/after it? Could you be a little more specific as to what you want to do? I can't tell if you're trying to update multiple documents (like, for a new company slogan or something) or output a bunch of documents based on a template like for a MailMerge type situation. – TheMadTechnician Feb 25 '14 at 00:11
  • For `.Find.Execute()` to make any changes you need to define both search and replacement text. And what do you mean by "middle of a document"? What do you want to insert, and where exactly? – Ansgar Wiechers Feb 25 '14 at 10:58
  • Thanks for the responses. I'm not looking to use .Find.Execute() to do a replacement of text. My example scenario is to have N paragraphs, followed by a Field/text marker/tag/etc., and have Word via the ComObject and PowerShell to start an insert of new .TypeParagraph(), .Table, etc., at the text marker, while pushing any data after the text document further down. This would be similar if I added a new Heading 1 in the document at, say, the third Heading 1, and start adding my text from there. Most examples I've seen are either initial inserts or full appends, not mid-document inserts. – Matt Feb 26 '14 at 05:09

0 Answers0