Generate Word documents with PowerShell

Sergei Dorogin
Sergei Dorogin’s technical blog
2 min readOct 14, 2016

--

In the previous post I mentioned that I was asked to produce a PDF document with source code for a library. In that post I reviewed how to detect and fix file encoding and process files line by line. In this post I’ll show how to create Word/PDF documents from PowerShell.

Here’s a complete script to dump text files into a Word document. It supposes that all files in UTF8 already.

Dump content of all text files into a Word document

Let’s go through the code.
First we need to create a document. To create a document we need to create a Word instance:

$word = New-Object -ComObject word.application
$word.Visible = $false
$doc = $word.documents.add()

As we have the document we can make some setup for default layout. I’m changing spacing between lines and make margins narrower:

$doc.Styles["Normal"].ParagraphFormat.SpaceAfter = 0
$doc.Styles["Normal"].ParagraphFormat.SpaceBefore = 0

$margin = 36 # 1.26 cm
$doc.PageSetup.LeftMargin = $margin
$doc.PageSetup.RightMargin = $margin
$doc.PageSetup.TopMargin = $margin
$doc.PageSetup.BottomMargin = $margin

To write text into the document we need Selection object:

$selection = $word.Selection

Having the selection it’s easy to put some text — method TypeText. To finish a paragraph we must call TypeParagraph.
Here we’re creating a heading (with a file name) and its content.

$selection.Style = "Heading 1"
$selection.TypeText($relativePath)
$selection.TypeParagraph()

$selection.Style = "Normal"
$selection.TypeText($temp);
$selection.TypeParagraph()

To save file (as docx):

$outputPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$outputPath = $outputPath + "sources.docx"
$doc.SaveAs($outputPath)
$doc.Close()
$word.Quit()

To save a file as PDF we’ll need to supply additional parameter for SaveAsmethod —wdFormatPDF value from WdSaveFormat enumeration. To use the enumeration we have to load its assembly:

Add-Type -AssemblyName "Microsoft.Office.Interop.Word"
$doc.SaveAs([ref]$outputPath, [ref] [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatPDF)
$doc.Close([Microsoft.Office.Interop.Word.WdSaveOptions]::wdDoNotSaveChanges)
$word.Quit()

Saving as PDF is actually “export” so if we just call Close() the Word instance will seem it hangs. Actually it’ll show save dialog somewhere in background. To prevent this we’re passing WdSaveOptions.wdDoNotSaveChanges.

--

--