Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word.Application ComObject errors in PowerShell

I'm unable to get a Word 2010 (14.0.x) document to SaveAs or Close using Powershell. From all the tuts online it seems like it should be working with 2.0, but I don't have that anymore.

Simple case:

$Path = "C:\MyDoc.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($Path)
$Doc.Close()

At this point everything works up until the saving and closing:

Argument: '1' should be a System.Management.Automation.PSReference. Use [ref].
At line:5 char:1
+ $Doc.SaveAs($Path)
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : NonRefArgumentToRefParameterMsg

Argument types do not match
At line:6 char:1
+ $Doc.Close()
+ ~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : Argument types do not match

It seems like any methods that Get-Member shows as having arguments fail. For instance, calling a simple $Doc.Save() works fine, it seems. Looking at the MSDN info on those methods it looks like it takes things like the SaveChanges method, but that's honestly beyond my skills at this point.

I've tried passing $Null or $True or $False in hopes of getting lucky, but it just keeps balking at me.

All I've been able to find is that it is apparently linked to PS 3.0 Beta (seems to work fine in 2.0 for people) and a comment Ed Wilson hasn't gotten back to.

like image 598
squid808 Avatar asked Oct 06 '22 19:10

squid808


2 Answers

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()
like image 90
spookycoder Avatar answered Oct 10 '22 03:10

spookycoder


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()
like image 39
latkin Avatar answered Oct 10 '22 04:10

latkin