Scripting >> Powershell >> Working with Microsoft Office Word document - Part 1

1.  Create a Word application object and make it visible

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True

 2.  Open a new Word document

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Add()



 

 3.  Open a new Word document and write some text and move to new paragraph

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Add()
$objSelection = $objWord.Selection
$objSelection.TypeText("Start of document.")
$objSelection.TypeParagraph()

 4.  Set style to "Heading 1" and type some text, change style to "Heading 2" type some text and change style to "Normal" and type some text

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Add()
$objSelection = $objWord.Selection
$objSelection.Style='Heading 1'
$objSelection.TypeText("Heading 1")
$objSelection.TypeParagraph()
$objSelection.Style='Heading 2'
$objSelection.TypeText("Heading 2")
$objSelection.TypeParagraph()
$objSelection.Style='Normal'
$objSelection.TypeText("Normal text")

5.  Open existing document, jump to the end of the document and clear all font and paragraph formatting before starting new text

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("c:\temp\mydocument.docx")
$objSelection = $objWord.Selection

$objSelection.EndKey(6,0)
$objSelection.TypeParagraph()
$objSelection.ClearFormatting()

6.  Set Bold, Italic and Bold-Italic font with different colors.

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("c:\temp\mydocument.docx")
$objSelection = $objWord.Selection

$objSelection.EndKey(6,0)
$objSelection.TypeParagraph()
$objSelection.ClearFormatting()

$objSelection.Font.Bold = 1
$objSelection.Font.Color=32768 # Green
$objSelection.TypeText('This is Bold Green Font')
$objSelection.Font.Bold = 0
$objSelection.TypeParagraph()

$objSelection.Font.Italic = 1
$objSelection.Font.Color=16711680 # Blue
$objSelection.TypeText('This is Italic Blue Font')
$objSelection.Font.Italic = 0
$objSelection.TypeParagraph()

$objSelection.Font.Bold = 1
$objSelection.Font.Italic = 1
$objSelection.Font.Color=-16777216 # automatic
$objSelection.TypeText('This is Bold Italic')
$objSelection.Font.Bold = 0
$objSelection.Font.Italic = 0
$objSelection.TypeParagraph()

7.  Open existing document, write some text and then save as new document

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("c:\temp\mydocument.docx")
$objSelection = $objWord.Selection

$objSelection.EndKey(6,0)
$objSelection.TypeParagraph()
$objSelection.ClearFormatting()
$objSelection.TypeText("Add some text")
$objSelection.TypeParagraph()


$FileSaveAs = 'c:\temp\mydocument-new.docx'
$wdFormatWordDefault = 16
$objDoc.SaveAs($FileSaveAs,$wdFormatWordDefault)

$objWord.ActiveDocument.Close()
$objWord.Quit()

8.  Open an existing document, search for keyword "document" and replace all with "word document", then save as new document

#
# syntax is
# find_object.Execute( _FindText_ , _MatchCase_ , _MatchWholeWord_ ,
#                     _MatchWildcards_ , _MatchSoundsLike_ , _MatchAllWordForms_ ,
#                     _Forward_ , _Wrap_ , _Format_ , _ReplaceWith_ ,
#                        _Replace_
, _MatchKashida_ , _MatchDiacritics_ ,
#                        _MatchAlefHamza_
, _MatchControl_ )
#
# Reference: https://docs.microsoft.com/en-us/office/vba/api/word.wdreplace
#

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("c:\temp\mydocument.docx")
$objSelection = $objWord.Selection

$FindText = "document"
$ReplaceWith = "word document"
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildCards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$wdFindContinue = 1
$Wrap = $wdFindContinue
$Format = $True
$wdReplaceNone = 0
$ReplaceAll = 2

$a = $objSelection.Find.Execute( $FindText,$MatchCase,$MatchWholeWord,
                                 $MatchWildCards,$MatchSoundsLike,
                                 $MatchAllWordForms,$Forward,$Wrap,
                                 $Format,$ReplaceWith,$ReplaceAll)

$FileSaveAs = 'c:\temp\mydocument-new.docx'
$wdFormatWordDefault = 16
$objDoc.SaveAs([ref]$FileSaveAs,[ref]$wdFormatWordDefault)
$objWord.Quit()

 9.   Discover information about tables in the document

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("report-template.docx")
$objSelection = $objWord.Selection

# list methods and properties of Tables object

> $objDoc.Tables | Out-GridView

10.  Jump to a Bookmark and then insert a text there.

$FilePath = "c:\temp\"
$FileName = "doc-with-bookmarks.docx"

$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open($FilePath + $FileName)
$objSelection = $objWord.Selection

$objDoc.Bookmarks.Item("Bookmark2").range.select()
$objSelection.TypeText("Inserted at Bookmark2")
 
 
 

 11.  How to insert an .XLSX document and .PDF document as a content (OLE object), displayed as icon at a bookmark location

$FilePath = "c:\temp\"
$FileName = "doc-with-bookmarks.docx"
$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open($FilePath + $FileName)
$objSelection = $objWord.Selection

#public Microsoft.Office.Interop.Word.InlineShape AddOLEObject
#( ref object ClassType,    ref object FileName,
#  ref object LinkToFile,   ref object DisplayAsIcon,
#  ref object IconFileName, ref object IconIndex,
#  ref object IconLabel,    ref object Range
#);

$ClassType     = "Excel.Sheet"  # obtain from assoc .xlsx
$FileName      = "c:\temp\test.xlsx"
$LinkToFile    = $False
$DisplayAsIcon = $True  
$IconFileName  = "c:\temp\excel-64px.ico"
$IconIndex     = 0
$IconLabel     = "System Availability Feb 2018"
$objDoc.Bookmarks.Item("Bookmark1").range.InlineShapes.AddOLEObject($ClassType,$FileName,$LinkToFile,$DisplayAsIcon,$IconFileName,$IconIndex,$IconLabel)

$ClassType     = "AcroExch.Document.DC"  #from registry HKCU\Software\Classes\.pdf
$FileName      = "c:\temp\test.pdf"
$LinkToFile    = $False
$DisplayAsIcon = $True  
$IconFileName  = "c:\temp\pdf-64px.ico"
$IconIndex     = 0
$IconLabel     = "Usage Stats Feb 2018"
$objDoc.Bookmarks.Item("Bookmark2").range.InlineShapes.AddOLEObject($ClassType,$FileName,$LinkToFile,$DisplayAsIcon,$IconFileName,$IconIndex,$IconLabel)
 


Before Insert

After Insert

 

12.  How to open a word document and set the active window position and size

$FilePath = "c:\temp\"
$FileName = "doc-with-bookmarks.docx"
$objWord = New-Object -ComObject Word.Application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open($FilePath + $FileName)
$objDoc.ActiveWindow.Left = 500
$objDoc.ActiveWindow.Width =650
$objDoc.ActiveWindow.Top = 0
$objDoc.ActiveWindow.Height = 620

$objDoc.ActiveWindow | foreach {"Top = " + $_.Top;"Left = " + $_.Left;
                                "Width = " + $_.Width;"Height = " + $_.Height;}

Ourput

Top = 0
Left = 500
Width = 650
Height = 620

 

wdReplace Enumeration

wdReplaceAll 2 Replace all occurrences.
wdReplaceNone 0 Replace no occurrences.
wdReplaceOne 1 Replace the first occurrence encountered.

 

wdFindWrap enumeration

wdFindAsk 2 After searching the selection or range, Microsoft Word displays a message asking whether to search the remainder of the document.
wdFindContinue 1 The find operation continues if the beginning or end of the search range is reached.
wdFindStop 0 The find operation ends if the beginning or end of the search range is reached.

 

Paragraph Alignment Enumeration

wdAlignParagraphCenter 1

Center-aligned.

wdAlignParagraphDistribute 4

Paragraph characters are distributed to fill the entire width of the paragraph.

wdAlignParagraphJustify 3

Fully justified.

wdAlignParagraphJustifyHi 7

Justified with a high character compression ratio.

wdAlignParagraphJustifyLow 8

Justified with a low character compression ratio.

wdAlignParagraphJustifyMed 5

Justified with a medium character compression ratio.

wdAlignParagraphLeft 0

Left-aligned.

wdAlignParagraphRight 2

Right-aligned.

wdAlignParagraphThaiJustify 9

Justified according to Thai formatting layout.

 

Color enumeration

wdColorAqua 13421619 Aqua color.
wdColorAutomatic -16777216 Automatic color. Default; usually black.
wdColorBlack 0 Black color.
wdColorBlue 16711680 Blue color.
wdColorBlueGray 10053222 Blue-gray color.
wdColorBrightGreen 65280 Bright green color.
wdColorBrown 13209 Brown color.
wdColorDarkBlue 8388608 Dark blue color.
wdColorDarkGreen 13056 Dark green color.
wdColorDarkRed 128 Dark red color.
wdColorDarkTeal 6697728 Dark teal color.
wdColorDarkYellow 32896 Dark yellow color.
wdColorGold 52479 Gold color.
wdColorGray05 15987699 Shade 05 of gray color.
wdColorGray10 15132390 Shade 10 of gray color.
wdColorGray125 14737632 Shade 125 of gray color.
wdColorGray15 14277081 Shade 15 of gray color.
wdColorGray20 13421772 Shade 20 of gray color.
wdColorGray25 12632256 Shade 25 of gray color.
wdColorGray30 11776947 Shade 30 of gray color.
wdColorGray35 10921638 Shade 35 of gray color.
wdColorGray375 10526880 Shade 375 of gray color.
wdColorGray40 10066329 Shade 40 of gray color.
wdColorGray45 9211020 Shade 45 of gray color.
wdColorGray50 8421504 Shade 50 of gray color.
wdColorGray55 7566195 Shade 55 of gray color.
wdColorGray60 6710886 Shade 60 of gray color.
wdColorGray625 6316128 Shade 625 of gray color.
wdColorGray65 5855577 Shade 65 of gray color.
wdColorGray70 5000268 Shade 70 of gray color.
wdColorGray75 4210752 Shade 75 of gray color.
wdColorGray80 3355443 Shade 80 of gray color.
wdColorGray85 2500134 Shade 85 of gray color.
wdColorGray875 2105376 Shade 875 of gray color.
wdColorGray90 1644825 Shade 90 of gray color.
wdColorGray95 789516 Shade 95 of gray color.
wdColorGreen 32768 Green color.
wdColorIndigo 10040115 Indigo color.
wdColorLavender 16751052 Lavender color.
wdColorLightBlue 16737843 Light blue color.
wdColorLightGreen 13434828 Light green color.
wdColorLightOrange 39423 Light orange color.
wdColorLightTurquoise 16777164 Light turquoise color.
wdColorLightYellow 10092543 Light yellow color.
wdColorLime 52377 Lime color.
wdColorOliveGreen 13107 Olive green color.
wdColorOrange 26367 Orange color.
wdColorPaleBlue 16764057 Pale blue color.
wdColorPink 16711935 Pink color.
wdColorPlum 6697881 Plum color.
wdColorRed 255 Red color.
wdColorRose 13408767 Rose color.
wdColorSeaGreen 6723891 Sea green color.
wdColorSkyBlue 16763904 Sky blue color.
wdColorTan 10079487 Tan color.
wdColorTeal 8421376 Teal color.
wdColorTurquoise 16776960 Turquoise color.
wdColorViolet 8388736 Violet color.
wdColorWhite 16777215 White color.
wdColorYellow 65535 Yellow color.

 

wdUnits enumeration (used by Selection.EndKey method)

wdCell 12 A cell.
wdCharacter 1 A character.
wdCharacterFormatting 13 Character formatting.
wdColumn 9 A column.
wdItem 16 The selected item.
wdLine 5 A line.
wdParagraph 4 A paragraph.
wdParagraphFormatting 14 Paragraph formatting.
wdRow 10 A row.
wdScreen 7 The screen dimensions.
wdSection 8 A section.
wdSentence 3 A sentence.
wdStory 6 A story.
wdTable 15 A table.
wdWindow 11 A window.
wdWord 2 A word.

 

wdExtend Enumeration

wdExtend 1

The end of the selection is extended to the end of the specified unit.

wdMove 0

The selection is collapsed to an insertion point and moved to the end of the specified unit. Default.

 

WdSaveFormat Enumeration

wdFormatDocument 0 Microsoft Office Word 97 - 2003 binary file format.
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.
wdFormatFlatXML 19 Open XML file format saved as a single XML file.
wdFormatFlatXML 20 Open XML file format with macros enabled saved as a single XML file.
wdFormatFlatXMLTemplate 21 Open XML template format saved as a XML single file.
wdFormatFlatXMLTemplateMacroEnabled 22 Open XML template format with macros enabled saved as a single XML file.
wdFormatOpenDocumentText 23 OpenDocument Text format.
wdFormatHTML 8 Standard HTML format.
wdFormatRTF 6 Rich text format (RTF).
wdFormatStrictOpenXMLDocument 24 Strict Open XML document format.
wdFormatTemplate 1 Word template format.
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.
wdFormatDocument97 0 Microsoft Word 97 document format.
wdFormatDocumentDefault 16 Word default document file format. For Word, this is the DOCX format.
wdFormatPDF 17 PDF format.
wdFormatTemplate97 1 Word 97 template format.
wdFormatXMLDocument 12 XML document format.
wdFormatXMLDocumentMacroEnabled 13 XML document format with macros enabled.
wdFormatXMLTemplate 14 XML template format.
wdFormatXMLTemplateMacroEnabled 15 XML template format with macros enabled.
wdFormatXPS 18 XPS format.

 

WdWindowState Enumeration (Word)

wdWindowStateMaximize 1 Maximized.
wdWindowStateMinimize 2 Minimized.
wdWindowStateNormal 0 Normal.

WdGoToDirection Enumeration (Word)

Specifies the position to which a selection or the insertion point is moved in relation to an object or to itself.

wdGoToAbsolute 1 An absolute position.
wdGoToFirst 1 The first instance of the specified object.
wdGoToLast -1 The last instance of the specified object.
wdGoToNext 2 The next instance of the specified object.
wdGoToPrevious 3 The previous instance of the specified object.
wdGoToRelative 2 A position relative to the current position.

 

WdParagraphAlignment enumeration (Word)

Name Value Description
wdAlignParagraphCenter 1 Center-aligned.
wdAlignParagraphDistribute 4 Paragraph characters are distributed to fill the entire width of the paragraph.
wdAlignParagraphJustify 3 Fully justified.
wdAlignParagraphJustifyHi 7 Justified with a high character compression ratio.
wdAlignParagraphJustifyLow 8 Justified with a low character compression ratio.
wdAlignParagraphJustifyMed 5 Justified with a medium character compression ratio.
wdAlignParagraphLeft 0 Left-aligned.
wdAlignParagraphRight 2 Right-aligned.
wdAlignParagraphThaiJustify 9 Justified according to Thai formatting layout.

WdVerticalAlignment enumeration (Word)

wdAlignVerticalBottom 3 Bottom vertical alignment.
wdAlignVerticalCenter 1 Center vertical alignment.
wdAlignVerticalJustify 2 Justified vertical alignment.
wdAlignVerticalTop 0 Top vertical alignment.

 

WdPageFit enumeration (Word)

Name Value Description
wdPageFitBestFit 2 Best fit the page to the active window.
wdPageFitFullPage 1 View the full page.
wdPageFitNone 0 Do not adjust the view settings for the page.
wdPageFitTextFit 3 Best fit the text of the page to the active window.

WdGoToItem Enumeration

Specifies the type of item to move the insertion point or selection just prior to.

Name Value Description
wdGoToBookmark -1 A bookmark.
wdGoToComment 6 A comment.
wdGoToEndnote 5 An endnote.
wdGoToEquation 10 An equation.
wdGoToField 7 A field.
wdGoToFootnote 4 A footnote.
wdGoToGrammaticalError 14 A grammatical error.
wdGoToGraphic 8 A graphic.
wdGoToHeading 11 A heading.
wdGoToLine 3 A line.
wdGoToObject 9 An object.
wdGoToPage 1 A page.
wdGoToPercent 12 A percent.
wdGoToProofreadingError 15 A proofreading error.
wdGoToSection 0 A section.
wdGoToSpellingError 13 A spelling error.
wdGoToTable 2

A table.