【问题标题】:Powershell Update Fields in Header and Footer in WordWord 中的页眉和页脚中的 Powershell 更新字段
【发布时间】:2014-09-13 07:18:43
【问题描述】:

我正在尝试使 Powershell 脚本正常工作,该脚本需要更新我在所有页面的页眉和页脚中拥有的所有字段。但即使经过数小时的研究,我也只能更新正文中的字段。当然,这真的很有用,而且我也在使用它,但我也想更新标题中的字段。

恐怕除了向您展示我拥有的用于更新文档中所有字段的 sn-p 之外,我无能为力。就这样吧。

objWord = New-Object -ComObject word.application
$objWord.ActiveDocument.Fields.Update() 

所以,请帮忙。

【问题讨论】:

标签: powershell com header ms-word footer


【解决方案1】:

从今天早上开始,我一直在四处寻找,找不到适合我的方法。 (与 OP 类似的请求)

我检查了 Adil 的链接,但它没有更新所有文档。

我需要更新添加到文档中的外部链接(对象)。正文、页眉和页脚需要更新,但是由于许多模板使用多个部分,我遇到了问题。

我认为在 Sections 循环期间有一些浪费,但它确保了整个文档的更新。

这是我的解决方案:

        # Open Word Instance (Use True for Debugging)
        $Word = New-Object -ComObject "Word.Application"
        $Word.Visible = $True

        # Open Template for Editing
        $Doc = $Word.Documents.Open($file.FullName)

        # Update Main Content
        $Word.ActiveDocument.Fields.Update() 

        # Iterate through Sections
        foreach ($Section in $Doc.Sections)
        {
            # Update Header
            $Header = $Section.Headers.Item(1)
            $Header.Range.Fields.Update()

            # Update Footer
            $Footer = $Section.Footers.Item(1)
            $Footer.Range.Fields.Update()
        }

        # Save and Close Template
        $Doc.Save()
        $Doc.Close() 

        # Exit Word Instance
        $Word.Quit()

【讨论】:

    【解决方案2】:

    上面的答案对我们的文档来说并不完全合适,但下面的答案是:

    $doc.Fields.Update() | Out-Null
    foreach ($section in $doc.Sections)
    {
        ForEach ($header in $section.Headers)
        {
            $header.Range.Fields.Update() | Out-Null
        }
        ForEach ($footer in $section.Footers)
        {
            $footer.Range.Fields.Update() | Out-Null
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2017-08-01
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多