PowerShell 中的 Word.Application ComObject 错误

squ*_*808 5 powershell comobject powershell-3.0

我无法使用 Powershell将 Word 2010 (14.0.x) 文档保存为另存为关闭。从网上的所有 tuts 看来,它应该可以与 2.0 一起使用,但我不再拥有它了。

简单案例:

$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()
Run Code Online (Sandbox Code Playgroud)

此时一切正常,直到保存和关闭:

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
Run Code Online (Sandbox Code Playgroud)

似乎 Get-Member 显示为有参数的任何方法都失败了。例如,调用一个简单的 $Doc.Save() 似乎工作正常。查看有关这些方法的 MSDN 信息,它看起来像SaveChanges方法之类的东西,但老实说,这超出了我目前的技能范围。

我试过传递 $Null 或 $True 或 $False 以期获得幸运,但它一直对我犹豫不决。

我所能找到的只是它显然与 PS 3.0 Beta 相关(似乎在 2.0 中对人们来说工作正常)并且Ed Wilson 还没有回复.

spo*_*der 3

我也为这个错误苦苦挣扎,但最终通过调用 PSReference 的“Value”属性解决了这个问题(我在这里获取了我的信息: https: //msdn.microsoft.com/en-us/library/system。 management.automation.psreference(v=vs.85).aspx )

这最终导致了代码行:

$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()
Run Code Online (Sandbox Code Playgroud)