Add Headers and Footers to Word Document with Power Shell

后端 未结 2 387
情书的邮戳
情书的邮戳 2021-01-28 08:55

I am looking for a way to insert headers and footers into a Microsoft Word document that was generated from within Power Shell. Is there a way to do this? If so, what is an ex

相关标签:
2条回答
  • 2021-01-28 09:09
    # Create a new Word application COM object
    $Word = New-Object -ComObject Word.Application;
    # Make the Word application visible
    $Word.Visible = $true;
    # Add a new document to the application
    $Doc = $Word.Documents.Add();
    # Get the first Section of the Document object
    $Section = $Doc.Sections.Item(1);
    # Get the header from the Section object
    $Header = $Section.Headers.Item(1);
    # Get the footer from the Section object
    $Footer = $Section.Footers.Item(1);
    
    # Set the text for the header and footer
    $Header.Range.Text = "Hey, I'm the header!";
    $Footer.Range.Text = "Hey, I'm the footer!";
    
    # Create a Table of Contents (ToC)
    $Toc = $Doc.TablesOfContents.Add($Section.Range);
    
    0 讨论(0)
  • 2021-01-28 09:18
    $Document = "c:\temp\tralala.doc" # Must exist
    
    $Word = New-Object -Com Word.Application
    $Word.Visible = $true
    $ExistingDoc = $Word.Documents.Open($document)
    $Selection = $Word.Selection
    $ExistingDoc.ActiveWindow.ActivePane.View.SeekView = 1
    $Selection.TypeText("Here is my automated header")
    $ExistingDoc.ActiveWindow.ActivePane.View.SeekView = 4
    $Selection.TypeText("Here is my automated footer")
    $ExistingDoc.Save()
    $Word.Quit()
    

    For having a list of possible values for SeekView, see here. WdSeekView section.

    0 讨论(0)
提交回复
热议问题