Word.Application ComObject errors in PowerShell Word.Application ComObject errors in PowerShell powershell powershell

Word.Application ComObject errors in PowerShell


I was also struggling al lot with this error, but got finally around it by calling the "Value" property of the PSReference (I got my Information here: https://msdn.microsoft.com/en-us/library/system.management.automation.psreference(v=vs.85).aspx )

this finally resulted in the codeLines:

$filename = [ref]"C:\Temp\pv_report.docx"    [ref]$option = [Microsoft.Office.Interop.Word.WdSaveFormat] -as [type]$document.SaveAs(([ref]$filename).Value, ([ref]$option::wdFormatDocumentDefault).Value)$document.Close()


You just need to use [ref] when you call SaveAs. This worked for me:

$Path = "C:\MyDoc.docx"$NewPath = "C:\MyDocRenamed.docx"$Word = New-Object -comobject Word.Application$Word.Visible = $True #Do this to close it out without task manager$Doc = $Word.Documents.Open($Path)$Doc.SaveAs([ref] $NewPath)$Doc.Close()


This might help you:

http://msdn.microsoft.com/en-us/library/office/cc626294(v=office.12).aspx#VSTO3PowerTools_OfficeInteropAPIExtensions

Office Interop API Extensions

The Office Interop API Extensions tool uses new features found in Microsoft .NET Framework 3.5 and Microsoft Visual C# 3.0 to wrap the Office object model and provide a more productive environment for the C# developer. Specifically, it employs extension methods, object initializers, and nullable types to create a simplified, strongly-typed, and, in some cases, Microsoft Visual Basic–like API. It is not a complete managed API for Office, but is designed to augment the raw object model in useful ways.

The Office object model was originally targeted at dynamic languages such as Microsoft Visual Basic for Applications (VBA) and Visual Basic. As such, it makes extensive use of some of their capabilities, such as late-binding and optional parameters. Being an early-bound and strongly-typed language, C# can be awkward, tedious, and error prone when used in this context. The Office Interop API Extensions, with its simplified and strongly-typed API, enables C# developers to be as productive in this context as Visual Basic developers.

I know PowerShell 3.0 is based off of CLR4, but this assembly should still load ok. It removes the need for all of the [ref] parameters. Since a lot of this API is based on extension methods (something that doesn't exist in powershell) you'll have to pass the $word or $doc instance as the first parameter for a lot of the methods.