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.TypeParagraph()
$myText.TypeText("This is on a new line!")
$myText.TypeParagraph()
$myText.TypeText("My username is $($Env:USERNAME) and the date is $(Get-Date)")
$myText.TypeParagraph()
# Start using bold
$myText.Font.Bold = 1
$myText.TypeText('Some Bold text.')
# Turn off bold
$myText.Font.Bold = 0
$myText.TypeParagraph()
# 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)
$mydoc.Close()
$MSWord.Quit()
# Clean up Com object
$null =
[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$MSWord)
Remove-Variable MSWord
| Name | Value | Description |
|---|---|---|
| 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.
New-Object - Create a new .Net object.