使用Powershell将AUTOTEXT添加到MS Word文档

时间:2012-05-25 20:58:58

标签: powershell scripting ms-word

我正在开发一个项目,我需要将类似X列表第1页的AUTOTEXT条目添加到Power Shell生成的MS Word文档的页眉和页脚中。我尝试从following C# examples中提取想法,但我似乎无法弄清楚如何使其发挥作用。我很好奇是否有人可以分享一些代码来帮助我。

1 个答案:

答案 0 :(得分:1)

一个起点。此函数将页码添加到作为参数传递的文档的页脚(在单词2010上使用):

function Add-PageFooter ([string]$Document) {

add-type -AssemblyName "Microsoft.Office.Interop.Word" 

set-variable -name wdAlignPageNumberCenter -value 1 -option constant

$fc1 =  "Page"

$word = New-Object -comobject Word.Application
$Word.Visible = $True
#$Word.Visible = $False

$fc2 = [ref] "" -as [Type]

$OpenDoc = $Word.Documents.Open($Document)
$c = $OpenDoc.Sections.Item(1).Footers.Item(1).PageNumbers.Add($wdAlignPageNumberCenter)
$range1 = $openDoc.Sections.Item(1).Footers.Item(1).range
$field1 = $OpenDoc.Fields.Add($range1, -1, $fc2)
$field1.Code.Text = $fc1
$field1.Update

#$OpenDoc.Close() 
}

另一种方法是创建一个Word Macro并从powershell执行:

$wd = new-object -comobject word.application # create a com object interface (word application)

$wd.documents.open("C:\word\test.doc") # open doc

$wd.run("Macro01") # exec macro named macro01 that add custom footer and/or header

$wd.quit() # exit application

macro必须保存在normal.dot(2010年及以上的normal.dotm)上才能将其保存在所有打开的文档中。

通过这种方式,您可以在Word文档中自定义您想要的内容,而不仅仅是在宏的页眉/页脚中录制文档中的操作。