troubleshooting Question

Filling word with powershell

Avatar of Christophe
ChristopheFlag for France asked on
Microsoft WordPowershell
6 Comments1 Solution2409 ViewsLast Modified:
Hello,

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

Christophe

# 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 = "microsoft.office.interop.word.WdSaveFormat" -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 = $word.documents.open($source)
$doc2 = $word2.Documents.add($template)
 
# Copy
$range = $doc.Range()
$copy = $range.Copy()
 
# Paste
$range2 = $doc2.Range()
$range2.Paste($copy)
 
# Save
$doc2.saveas([ref]$destination, [ref]$saveFormat::wdFormatDocument)
 
# Close Word
$word.Application.ActiveDocument.Close()
$word.Quit()
$word2.Application.ActiveDocument.Close()
$word2.Quit()
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 6 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros