gpt4 book ai didi

powershell - PowerShell 中的 Word.Application ComObject 错误

转载 作者:行者123 更新时间:2023-12-01 02:32:39 25 4
gpt4 key购买 nike

我无法将 Word 2010 (14.0.x) 文档发送到 SaveAsClose使用 Powershell。从网上的所有 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()

此时一切正常,直到保存和关闭:
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

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

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

我能找到的只是它显然是 linked to PS 3.0 Beta (似乎在 2.0 中对人们工作正常)和评论 Ed Wilson hasn't gotten back to .

最佳答案

我也为这个错误苦苦挣扎,但最终通过调用 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()

关于powershell - PowerShell 中的 Word.Application ComObject 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com