Avatar of Christophe
Christophe
Flag for France

asked on 

Filling word with powershell

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()

Open in new window

PowershellMicrosoft Word

Avatar of undefined
Last Comment
GrahamSkan

8/22/2022 - Mon