Integrate Microsoft Word with PowerShell: Format Style Documents

In Part 1 of this two-part series, we looked at the basics of creating a Microsoft Word document from Windows PowerShell. If you tried out my sample commands you noticed that the formatting left a little something to be desired. Fortunately, there are some easy steps you can take to improve the quality of your document, and I’ll show you those in this post. We’ll use the script from Part 1 as a starting point.

The key is the selection object.

​PS C:\>$word=new-object -ComObject "Word.Application"
PS C:\>$doc=$word.documents.Add()
PS C:\> $selection=$word.Selection

One important element you can modify with the selection object is the Font. You can easily modify the font size and color, as well as what font to use. I’m going to set the font for the date and time to be Green.

​PS C:\> $selection.Font.Color="wdColorGreen"
PS C:\> $selection.TypeText((Get-Date))

In the days of VBScript we would have had to identify the value of wdColorGreen and define a constant. But in PowerShell we can simple insert the constant as a string. Curious about the color choices? Ask PowerShell:

​PS C:\> [enum]::GetNames([])

Unless you want the entire document in this font color, you’ll need to set it back.

​PS C:\ >$selection.font.Color="wdColorAutomatic"
PS C:\> $selection.TypeParagraph()

In my original script I inserted a title. This time let’s make it stand out a bit with a larger font. I’ll use the same WMI code as I did last time.

$selection.TypeText("Operating System Information for $($os.CSName)")

If you recall from last time, one issue when writing PowerShell output to Word is the former uses fixed width fonts and the latter used variable width. The solution is to specify an appropriate font before inserting results from PowerShell.

​PS C:\> $selection.Font.Size=10
PS C:\> $selection.Font.Name="Consolas"
PS C:\> $selection.TypeText(($os | Select -Property $props | Out-String))

The last thing I want to add is another formatted piece of text that shows who created the report. I want this to be in a Word font formatted as italics.

​PS C:\> $selection.Font.size=8
PS C:\> $selection.Font.Name="Calibri"
PS C:\> $selection.Font.Italic=$True
PS C:\> $by="Report created by $env:userdomain\$env:username"
PS C:\> $selection.TypeText($by)

I bet you can figure out how to make something bold.
In addition to specific font changes you can also use Word’s built in styles.

$selection.TypeText("Operating System Report")

You can ask PowerShell for a list of styles using the document object.

​$doc.Styles | select NameLocal

Most of these styles should only apply to the first line of text but it might take some testing on your part to fine tune.
With these steps you can easily create nice looking Word documents from your PowerShell scripts. Download the revised version of my script, New-WordDoc2, and try it out for yourself.