Powershell Update Fields in Header and Footer in W

2019-08-03 06:43发布

I'm trying to get a Powershell Script working that needs to update all fields I have in Header and Footers of all pages. But even after hours of research, I don't get any farther than being able to update the fields in the main text. Sure, that is really useful and everything and I am using it as well, but I would also like to update the fields in the headers.

I'm afraid I can't be of much help other than showing you the snippet I have that updates all my fields in the document. So here goes that.

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

So, please, help.

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-03 07:18

I have been looking around since this morning and cannot find a approach that works for me. (Similar request to OP)

I have checked Adil's link however it did not update all of the document.

I needed to update external links (Objects) that I added to documents. Body, Headers and Footers need to be updated, however since many of the templates use multiple sections I was having issues.

I believe there is some waste during the Sections loop however it ensures that the entire document is updated.

Here is my solution:

        # 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()
查看更多
走好不送
3楼-- · 2019-08-03 07:22

The answer above didn't quite cut it for our docs, but the following did:

$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
    }
}
查看更多
登录 后发表回答