JoeG
JoeG

Reputation: 4247

Add a header to a Word document?

I would like to add a custom header to a .doc file using PowerShell (I mean the actual Header, not a heading). This SHOULD work:

$Word=New-Object -ComObject "Word.Application"
$wdSeekPrimaryHeader = 1
$Doc=$Word.Documents.Open("C:\test.doc")
$Selection=$Word.Selection
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
$Selection.TypeText("Text")
$doc.close([ref]$Word.WdSaveOptions.wdDoNotSaveChanges)
$word.quit()

But it doesn't. It actually does nothing that I can tell.

Any ideas on what I'm doing wrong here?

Here is the code that works:

$Word=New-Object -ComObject "Word.Application"
$wdSeekPrimaryHeader = 1
$Doc=$Word.Documents.Open("C:\test.doc")
$Selection=$Word.Selection
$Doc.ActiveWindow.ActivePane.View.SeekView=$wdSeekPrimaryHeader
$Selection.TypeText("Text")
$Doc.Save()
$Doc.Close()
$Word.Quit()

Thanks again peeps!

Upvotes: 2

Views: 1946

Answers (2)

PeskyGnat
PeskyGnat

Reputation: 2464

I get an error on the [ref] (Argument: '1' should not be a System.Management.Automation.PSReference. Do not use [ref].) If I replace the close(..) line with:

$doc.save()
$doc.close()

Then I see the header

Upvotes: 1

Matt
Matt

Reputation: 1969

I'm not sure the [ref] works anyway but you've got it referencing DoNotSaveChanges. wouldn't you want save changes?

Upvotes: 2

Related Questions