Insert object in Word document with Powershell

At times, you have to create reports in Word format. If these are reports you have to create on a regular basis, you’ll want to automate this as much as possible. There is a lot you can do to automate this process with Powershell. There are some excellent resources available to get started, such as this one:

Beginning with PowerShell and Word

This week, I had to make a report with embedded objects. In Word, you can do this with Insert > Object… .  The method to call is AddOLEObject. And though this method is documented (link for Office 2013 & above), and there are plenty of code examples out there on the internet on how to call this method using, for example, C# or VBA, I could not find an example on how to call this method using Powershell. I had to work out the exact syntax using trial and error. So I decided to write this blog post to help others out there with the exact syntax. Here it is:

$Selection.InlineShapes.AddOLEObject("excel.sheet","E:\data.xlsx","False","True",$iconfile, 0,"some caption text")

A short explanation of the syntax. Following the example of the first link provided above, $Selection is the variable containing the Word object. The first parameter is the class type, in this case “excel.sheet”. The second variable is the name of the file. The third and fourth parameter are LinkToFile and DisplayAsIcon. As explained in the DevCenter web page, this determines whether the file is added, or the content of the file. The fifth parameter, IconFileName, should link to the file containing the icons. For Word 2016, this is C:\Program Files (x86)\Microsoft Office\root\Office16\Wordicon.exe. For Excel 2016, this is XLSICON.exe in the same directory. For other Office version, this location will be different.


This entry was posted in Code samples, Powershell. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *