PowerShell Pipeline

Getting Started with Word Using PowerShell

Here's how to automate building a document in Microsoft Word. Clippy not required.

Whenever someone brings up using PowerShell to automate an Office product, often what you may think of initially ends up being along the lines of working with Excel instead of Word.

And there is good reason for this, as Excel allows you to bring in a lot of data to generate reports and graphs that you can then send to someone or use to update another form with a generated graph.

Today, I will be stepping away from Excel as the Office automated tool using PowerShell, and instead look at how you can use Word with PowerShell to create a document -- or, at the very least, get you started on the path to creating an automated approach to building a document.

One of the first things that you need to do is ensure that you have Word installed on your computer. Once you have that verified, we can begin by creating a COM object connection to Word.Application, which is what we will then use to begin interacting with Word.

PS C:\> $Word = New-Object -ComObject Word.Application
PS C:\> $Word
Application                       : Microsoft.Office.Interop.Word.ApplicationClass
Creator                           : 1297307460
Parent                            : Microsoft.Office.Interop.Word.ApplicationClass
Name                              : Microsoft Word
Documents                         : System.__ComObject
Windows                           : System.__ComObject
ActiveDocument                    :
ActiveWindow                      :
Selection                         :
WordBasic                         : System.__ComObject
RecentFiles                       : System.__ComObject
NormalTemplate                    : System.__ComObject
System                            : System.__ComObject
AutoCorrect                       : System.__ComObject
FontNames                         : System.__ComObject
LandscapeFontNames                : System.__ComObject
PortraitFontNames                 : System.__ComObject
Languages                         : System.__ComObject
Assistant                         : System.__ComObject
Browser                           : System.__ComObject
FileConverters                    : System.__ComObject
MailingLabel                      : System.__ComObject
Dialogs                           : System.__ComObject
CaptionLabels                     : System.__ComObject
AutoCaptions                      : System.__ComObject
AddIns                            : System.__ComObject
Visible                           : False
Version                           : 15.0
ScreenUpdating                    : True
PrintPreview                      : False
Tasks                             : System.__ComObject

If we were running a script that was just looking to create the document without showing anything, we would just leave the Visible property on the object to False. Since this is all about interacting with Word and showing things that we are doing, we will go ahead and set this to $True. In doing so, Word will now appear on our screen.

$Word.Visible = $True

We are almost to the point to where we can start making some edits on the document, but before we do that, we need to add a document to our Word object and then select it so we can being adding text to it.

$Document = $Word.Documents.Add()
$Selection = $Word.Selection

We are now ready to begin writing in our Word document! For fun, I will type out my username into Word and the current date. I can do this using the TypeText() method, which is available on my object.

$Selection.TypeText("My username is $($Env:USERNAME) and the date is $(Get-Date)").

Let's see if it worked out.

[Click on image for larger view.]

It sure looks like it typed out everything that I was adding to the TypeText method. It typed out the user name and date, even though both were variables that I had to expand out in the text.

Something to keep in mind is that if I make use of the TypeText method again, the text will appear on the same line as the rest of the text. If you are looking to start on a new line, then you should look at using the TypeParagraph method and then use TypeText to begin writing on a brand-new line.

$Selection.TypeParagraph()
$Selection.TypeText("This is on a new line!")
$Selection.TypeParagraph()
$Selection.TypeParagraph()
$Selection.TypeText("Yet another line to type on!")

The last thing that I will cover today is working with some of the fonts like bold and italics to add some extra spice to your writing. The trick here is to declare your font style prior to writing using TypeText so that you will have the proper font type when your text is written, much like when you were to type out text in Word yourself.

In this case, I will write out a line in italics and then in bold.

$Selection.TypeParagraph()
$Selection.Font.Bold = 1
$Selection.TypeText(Here is something that I felt should be in Bold)
$Selection.Font.Bold = 0
$Selection.TypeParagraph()
$Selection.Font.Italic = 1
$Selection.TypeText(Just some fun text that is now in Italics!)

Lastly, we should probably save our work so that we can send it to whomever might need it. I'll use the SaveAs method on my Document object and supply the full path to where the document will be saved to, as well as the file name. I'll also tell the method what kind of format to save the document in. Once I do that, I am free to quit Word by calling Quit() under my word object.

$Report = C:\temp\MyFirstDocument.docx
$Document.SaveAs([ref]$Report,[ref]$SaveFormat::wdFormatDocument)
$word.Quit()

Because working with COM objects can be unique sometimes, we will take an extra step and do some clean-up actions to ensure that nothing is left behind to hang around in memory.

$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$word)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable word

All done! We have now taken our first step into the fun world of working with Word using PowerShell.

About the Author

Boe Prox is a Microsoft MVP in Windows PowerShell and a Senior Windows System Administrator. He has worked in the IT field since 2003, and he supports a variety of different platforms. He is a contributing author in PowerShell Deep Dives with chapters about WSUS and TCP communication. He is a moderator on the Hey, Scripting Guy! forum, and he has been a judge for the Scripting Games. He has presented talks on the topics of WSUS and PowerShell as well as runspaces to PowerShell user groups. He is an Honorary Scripting Guy, and he has submitted a number of posts as a to Microsoft's Hey, Scripting Guy! He also has a number of open source projects available on Codeplex and GitHub. His personal blog is at http://learn-powershell.net.

comments powered by Disqus
Most   Popular