Beginning with PowerShell and Word

This first article will dip our toes into creating the Word Com object, looking at sending text to Word and adjusting some of the various fonts and styles to give you a stepping stone on what you can do. I will be using Word 2013 in this article, so your mileage may vary if using older versions.

Creating the Word Object

Like any COM object, we must use New-Object with the –ComObject parameter to tell PowerShell that we are loading up a Com object.

 
$Word = New-Object -ComObject Word.Application

Now I have created my object as shown in the image below.

image

One thing that you might note is that we can’t see Word opened up, even though the process is actually active.

image

To make Word visible, we have to set the Visibility of the object to $True.

 
$Word.Visible = $True

Now you should see that Word is visible. But we don’t actually have a document loaded yet to start writing. We need to fix that first. We do this by calling the Documents.Add() method. I am keeping the output of this saved to another variable that will be used later on. I then want to select the current pane in Word so I can begin writing data to it.

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

Writing to Word

Writing to word is as simple as calling TypeText() and supplying a parameter which is text.

 
$Selection.TypeText("Hello")

image

Ok, nothing really mind blowing here, but this is how we can write in word using PowerShell. If I attempt to do this again, it will not actually start on the next line but append to the existing line.

image

We work around this by calling TypeParagraph().

 
$Selection.TypeParagraph()
$Selection.TypeText("Hello1")
$Selection.TypeParagraph()
$Selection.TypeParagraph()
$Selection.TypeText("Hello2")
$Selection.TypeParagraph()
$Selection.TypeParagraph()
$Selection.TypeText("Hello3")
$Selection.TypeParagraph()

image

Working with Styles

So lets start with a fresh slate (actually I am just going to delete all of the words here instead of rebuilding the object) and look at some of the Styles that we can use.

First off, we should see what kind of styles are available to use.

 
[Enum]::GetNames([Microsoft.Office.Interop.Word.WdBuiltinStyle]) | ForEach {
    [pscustomobject]@{Style=$_}
} | Format-Wide -Property Style -Column 4

image

This is just one of the possible options to set a style that also includes using an integer or a string value that matches the names of what you would see in the toolbar for styles.

image

Whatever approach you are comfortable with will be just fine. Just make sure if it the setting isn’t that readable (such as using an integer) that you comment what the style is supposed to be for whoever might be looking at the code later on.

Moving on from that, we will set a couple of styles to show off what we can do. I think we at least need a Title and perhaps some sort of Header to show off what we are doing.

 
$Selection.Style = 'Title'
$Selection.TypeText("Hello")
$Selection.TypeParagraph()
$Selection.Style = 'Heading 1'
$Selection.TypeText("Report compiled at $(Get-Date).")
$Selection.TypeParagraph()

image

Feel free to explore and find some styles that will work with what you are trying to do!

Exploring Fonts

The last item that I will cover today is working with Fonts such as changing the color and going with Bold or Italics.

We can locate the fonts using $Selection.Font

 
$Selection.Font

image

Ok, there is obviously a lot of stuff available here that we can manipulate, but I just focus on the basics. Notice that the Bold and Italic are specified by an integer. Currently, a 0 means that this is turned off. If we want to turn it on, we specify something other than a 0, such as a 1.

 
$Selection.Font.Bold = 1
$Selection.TypeText('This is Bold')
$Selection.Font.Bold = 0
$Selection.TypeParagraph()
$Selection.Font.Italic = 1
$Selection.TypeText('This is Italic')

image

Lastly, we will check out adjusting the colors of the text in word and we can find out the available colors using the following code:

 
[Enum]::GetNames([Microsoft.Office.Interop.Word.WdColor]) | ForEach {
    [pscustomobject]@{Color=$_}
} | Format-Wide -Property Color -Column 4

image

Now we can write some code to take a look at some of these colors.

 
[Enum]::GetNames([Microsoft.Office.Interop.Word.WdColor]) | ForEach {
    $Selection.Font.Color = $_
    $Selection.TypeText("This is $($_)")
    $Selection.TypeParagraph()    
} 
$Selection.Font.Color = 'wdColorBlack'
$Selection.TypeText('This is back to normal')

SNAGHTML48723c4d

Actually, I decided to just go through all of the colors so we can see each and every one!

One last thing! It may be a good idea to save our good work so we can view it later, right? So with that we can use the following code to save the document. We do this using the SaveAs method in the $Document object that we had created earlier. Aren’t you glad we saved that output earlier?

We do need to specify a reference variable which is the path and name of the file as well as a second parameter specifying the save format of the document. as…you guest it…another reference variable! We can find the possible format types using this code.

 
[Enum]::GetNames([microsoft.office.interop.word.WdSaveFormat])

image

And now I can save this document using the following code:

 
$Report = 'C:\Users\proxb\Desktop\ADocument.doc'
$Document.SaveAs([ref]$Report,[ref]$SaveFormat::wdFormatDocument)
$word.Quit()

I am calling the Quit() method to actually quit the application. Unfortunately, this doesn’t actually mean that the memory used to create this object has been freed up. Com objects play a little differently than .Net objects that we create. So with that in mind, I am going to do the following to free up that memory:

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

There you go! That was a little dip into the pool of PowerShell and Word to get you going on building out something cool!

About Boe Prox

Microsoft Cloud and Datacenter MVP working as a SQL DBA.
This entry was posted in powershell and tagged , , . Bookmark the permalink.

4 Responses to Beginning with PowerShell and Word

  1. Pingback: Creating a Table of Contents in Word Using PowerShell | Learn Powershell | Achieve More

  2. texellis says:

    I had to first load the assembly before enumerating the styles:
    Add-Type -AssemblyName Microsoft.Office.Interop.Word

    • Boe Prox says:

      Thanks for sharing that! I didn’t run into that because i had already loaded the assembly when i created the word object. Definitely good to know!

      • williamyun7 says:

        Thanks for the great tip. I would like to know if there is a way I can access a Word object which is currently running on my system. Say I am currently editing a Word and want to access this Word object by a script so I can make it save automatically with the script.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s