Add a header to a Word document?

风流意气都作罢 提交于 2019-12-24 12:18:45

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/6221783/add-a-header-to-a-word-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!