gpt4 book ai didi

PowerShell - 处理多个 word 文档 (office 2010)

转载 作者:行者123 更新时间:2023-12-02 23:30:39 24 4
gpt4 key购买 nike

我正在尝试编写一个 PowerShell 脚本来对多个 Word 文档执行步骤。我的机器上安装了 Word 2010,但我似乎无法获取打开文档的脚本。这是脚本

    $path = "C:\MyPath" 
Add-Type -AssemblyName Microsoft.Office.Interop.Word
$wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
$objWord = New-Object -ComObject "word.application"
$objWord.visible = $false
foreach($wd in $wordFiles)
{
$doc = $objWord.documents.open($wd.fullname)
#InsertProcessingFunctionsHere
$doc.Save()
$objWord.Documents.Close()
}
$objWord.Quit()

我尝试运行它,我从 PowerShell 返回的错误是:

    Exception calling "Open" with "1" argument(s): "Command failed"
At C:\Scripts\Process-WordDocs.ps1:10 char:31
+ $doc = $objWord.documents.open <<<< ($wd.fullname)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation

You cannot call a method on a null-valued expression.
At C:\Scripts\Process-WordDocs.ps1:13 char:10
+ $doc.Save <<<< ()
+ CategoryInfo : InvalidOperation: (Save:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

Exception calling "Close" with "0" argument(s): "This method or property is not available because a document window is not active."
At C:\Scripts\Process-WordDocs.ps1:14 char:25
+ $objWord.Documents.Close <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation

MSDN 指出 documents.open 只需要 1 个参数,其余的都是可选的。但是,我在网上看到的一个 C# 示例显示将“ReadOnly: False”参数传递给 documents.open。通过 ISE 调试器中的脚本,我可以看到 $wd.fullname 在那里并指向一个有效文件,所以我完全不清楚为什么它没有打开。起初,我以为这是因为我使用的是 64 位版本的操作系统(32 位版本的 Office),但尝试从 32 位 PowerShell session 中执行脚本导致了同样的错误。任何人都知道为什么会发生这种情况,我该如何解决?我希望所有处理过程都对用户不可见。任何帮助将非常感激。预先感谢您的宝贵时间。

最佳答案

我认为您想使用 $doc.close() 而不是 $objWord.Documents.Close()

关闭文档

关于PowerShell - 处理多个 word 文档 (office 2010),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11563536/

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