How-to: How to automate Microsoft Word in PowerShell using a COM object.

For the script below to work, the computer will need to have a copy of Microsoft Word already installed.

This example open a new document, types in some formatted text and saves the file, you can modify this to do more complex tasks.

# Create a new instance/object of MS Word
$MSWord = New-Object -ComObject Word.Application

# Make MS Word visible
$MSWord.Visible = $True

# Add a new document
$mydoc = $MSWord.Documents.Add()

# Create a reference to the current document so we can begin adding text
$myText = $MSWord.Selection

# Add some text with new paragraphs in between.
$myText.TypeText("This is on a new line!")
$myText.TypeText("My username is $($Env:USERNAME) and the date is $(Get-Date)")

# Start using bold
$myText.Font.Bold = 1
$myText.TypeText('Some Bold text.')

# Turn off bold
$myText.Font.Bold = 0

# Start using Italic
$myText.Font.Italic = 1
$myText.TypeText('Some italic text.')

# Save and quit
$filename = 'C:\work\Demo99.docx'
$saveFormat = [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatDocumentDefault
$mydoc.SaveAs([ref][system.object]$filename, [ref]$saveFormat)

# Clean up Com object
$null =
Remove-Variable MSWord

WdSaveFormat Enumeration

Name Value 18Description
wdFormatDocument 0 Microsoft Office Word format (.Doc).
wdFormatDocument97 0 Microsoft Word 97 document format (.Doc).
wdFormatDOSText 4 Microsoft DOS text format.
wdFormatDOSTextLineBreaks 5 Microsoft DOS text with line breaks preserved.
wdFormatEncodedText 7 Encoded text format.
wdFormatFilteredHTML 10 Filtered HTML format.
wdFormatHTML 8 Standard HTML format.
wdFormatRTF 6 Rich text format (RTF).
wdFormatTemplate 1 Word template format (.Dot).
wdFormatText 2 Microsoft Windows text format.
wdFormatTextLineBreaks 3 Windows text format with line breaks preserved.
wdFormatUnicodeText 7 Unicode text format.
wdFormatWebArchive 9 Web archive format.
wdFormatXML 11 Extensible Markup Language (XML) format.
wdFormatDocumentDefault 16 Word default document file format.
For Word 2007+, this is .Docx
wdFormatPDF 17 PDF format.
wdFormatTemplate97 1 Word 97 template format (.dot).
wdFormatXMLDocument 12 XML document format (.docx).
wdFormatXMLDocumentMacroEnabled 13 XML document format with macros enabled (.docm).
wdFormatXMLTemplate 14 XML template format (.dotx).
wdFormatXMLTemplateMacroEnabled 15 XML template format with macros enabled (.dotm).
wdFormatXPS 18 XPS format.

“A word and a stone let go cannot be recalled” ~ Spanish Proverb.

Related PowerShell Cmdlets:

New-Object - Create a new .Net object.

Copyright © 1999-2022
Some rights reserved