【问题标题】:How to connect Powershell script to an already opened document?如何将 Powershell 脚本连接到已打开的文档?
【发布时间】:2023-03-29 13:20:01
【问题描述】:

我有一个 Powershell 脚本,它使用 MSWord 文档执行一些修改。在脚本的开头 PS 打开文档:

$word = New-Object -ComObject Word.Application
$desktop_path = [Environment]::GetFolderPath("Desktop")
$doc = $word.Documents.Open("$desktop_path" + "blabla.docx")

但是随着需求的变化,我现在需要在一个已经打开的文档中运行这个 PS 脚本。是否有任何选项可以强制PowerShell 查找打开的文档(例如通过名称)并“连接”到它?

仅供参考:我想要获得的序列是:我打开文件,启动一些宏,从 VBA 调用我的 PSScript(这里我需要 PS 能够“获取”打开的文档),启动其他宏。

非常感谢您!

【问题讨论】:

  • 为什么不更改顺序以通过 powershell 运行宏? $doc.run("Macro01") 运行一个名为“Macro01”的宏?
  • 感谢您的回复。关键是宏是使用热键启动的,这取决于用户的选择......并且通过PS执行了一些功能,无论如何,我会考虑的,谢谢。

标签: powershell ms-word office-interop com-interop


【解决方案1】:

这应该和for Excel一样:

$word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')

注意同一用户的限制。我建议通过 PowerShell 以编程方式完成整个操作,as suggested by Guenther

如果 word 没有运行,在不同的用户下运行,或者以管理员身份运行(并且 PowerShell 没有以管理员身份运行),您将收到错误:

Exception calling "GetActiveObject" with "1" argument(s): "Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))"
At line:1 char:1
+ $word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Appl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : COMException

按照建议,检查 PowerShell 和 Word 是否在同一用户下运行。您可以通过转到任务管理器 > 详细信息并检查用户名列中的 WINWORD.EXEpowershell.exe 来实现这一点

根据名称获取特定文档:

$doc = $word.Documents | Where-Object {$_.Name -eq "Document2"}

您可以通过查看计数来检查打开了多少文档:

$word.Documents.Count

【讨论】:

  • 当我这样做时: Add-Type -AssemblyName "Microsoft.Office.Interop.Word" $word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('Word.Application') $doc = $word.ActiveDocument(),我收到消息“此命令不可用,因为没有打开文档。”但是有一个打开的文档,问题是 - 如何连接到它。
  • 谢谢,是的,它完美运行: $word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application') $doc = $word.Documents | Where-Object {$_.Name -eq "HANA_TPO"} 祝你好运!
猜你喜欢
  • 1970-01-01
  • 2013-05-17
  • 2022-10-14
  • 1970-01-01
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
相关资源
最近更新 更多