Filling word with powershell


I would like to fill a word document with powershell. I have specified bookmarks in my word's template. I would like my script pulls data from another file, populates bookmarks in word template and saves a new word document in a sharepoint website.

I have started with the script below to try but I do not know how I can manage bookmarks. About saving to sharepoint location it is a second step and I will try to find solution.

Thank you in advance for your help


# Variables used to get text from text file

$Title = get-content "C:\location\source.txt" | Select -Index 0
$LineOne = get-content "C:\location\source.txt" | Select -Index 1
$LineTwo = get-content "C:\location\source.txt" | Select -Index 2
$LineThree = get-content "C:\location\source.txt" | Select -Index 3
$Date = get-content "C:\location\source.txt" | Select -Index 4

$source = "C:\location\source.txt"
$destination = "C:\user\Downloads\newfile.docx"
$template = "C:\location\template.dotx"
[ref]$SaveFormat = "" -as [type]
# Open Word
$word = New-Object -comobject word.application
$word.visible = $false
$word2 = New-Object -ComObject word.application
$word2.visible = $false
# Create new from template
$doc = $$source)
$doc2 = $word2.Documents.add($template)
# Copy
$range = $doc.Range()
$copy = $range.Copy()
# Paste
$range2 = $doc2.Range()
# Save
$doc2.saveas([ref]$destination, [ref]$saveFormat::wdFormatDocument)
# Close Word

Open in new window

ChristopheIT CoordinatorAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NorieAnalyst Assistant Commented:

You should be able to use something like this to work with bookmarks.
$doc2.Bookmarks.Item("MyBookMark").Range.Text = "MyText"

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ChristopheIT CoordinatorAuthor Commented:
Hello Norie,

Thank you for your help. I am trying your solution but it does not work. I am not sure how I can implement your code.

Could you give me an example?

NorieAnalyst Assistant Commented:

What exactly did you try and how did it not work?
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

ChristopheIT CoordinatorAuthor Commented:

I have created a bookmark in word template. Bookmark is named T2

# Paste
$range2 = $doc2.Bookmarks.Item("T2").Range.Text = "MyText"

Open in new window

The requested member of the collection does not exist.
At H:\Scripts\Jaquettes\cdtest.ps1:31 char:11
+ $range2 = $doc2.Bookmarks.Item("T2").Range.Text = "MyText"
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At H:\Scripts\Jaquettes\cdtest.ps1:32 char:1
+ $range2.Paste($copy)
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
NorieAnalyst Assistant Commented:

Here is a very simple example with a document containing a bookmark named 'T2'.
# Open Word and set text of bookmark
$newtext = "This is the new text."
$word = New-Object -comobject word.application
$word.visible = $true
$doc = $"C:\test\test.docx")
$bookmark = $doc.Bookmarks("T2")
$bookmark.Range.Text = $newtext

Open in new window

Are you sure that the bookmark does exist?

I don't know Powershell, but it must use the Word Object Model in a similar way to VBA.

The VBA code that Norie has  posted will work - once. However it is likely to overwrite the bookmark itself, so that it isn't there for a second attempt. I use a procedure like this:
Sub FillBookmark(doc As Document, strBookMark As String, strNewText As String)
    Dim rng As Range
    Set rng = doc.Bookmarks(strBookMark).Range
    rng.Text = strNewText
    doc.Bookmarks.Add strBookMark, rng 're-add the bookmark in case it was overwritten
End Sub

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.