Powershell - 将新文档添加到页码为2的现有word文件中

时间:2014-11-04 14:11:00

标签: powershell ms-word

我正在尝试打开现有的word文件并向其添加新页面。这个新页面将包含一些内容,我总是希望此页面位于第2位。因此,第一页将始终相同,并且添加的每个新内容都应转到第二页。到目前为止,我的代码如下:

$day = get-date -Format "dd-MMM-yyyy"
$filedate = Get-Date -Format "dd/MMM/yy - H tt"
$word = New-Object -ComObject word.application
$word.visible = $false
$doc = $word.documents.open("$home\desktop\Network Report.docx")
$selection = $word.selection
$Selection.InsertNewPage() #So, this page should be added at number 2
$selection.Font.Size = 14 
$selection.Font.color ="wdColorBlack"
$selection.TypeText("Network Report for $filedate")
$selection.TypeParagraph()
$selectimage =  $selection.InlineShapes.AddPicture("$home\desktop\screenshot.jpeg")
$selection.TypeParagraph()
$Section = $Doc.Sections.Item(1);
$Header = $Section.Headers.Item(1);
$Footer = $Section.Footers.Item(1);
$Header.Range.Text = "$campus Network Report - $day "
$doc.save()

经过不同的表格后,我尝试了不同的追随者:

$gotoPage1 = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage 
$gotoNext1 = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute
$gotoCount1 = null
$gotoName1 = 1
$Selection.GoTo([ref]$gotoPage1, [ref]$gotoNext1, [ref]$gotoCount1, [ref]$gotoName1)

但我没有运气。如何添加新页面作为第二页?

1 个答案:

答案 0 :(得分:0)

这是一个应创建第二页的示例,并将光标放在那里。无论文档中的页数是多少,这都应该有效。

$word = New-Object -ComObject word.application
$word.Visible = $true

$doc = $word.documents.open("$home\desktop\Network Report.docx")

[Void]$word.Selection.GoTo([Microsoft.Office.Interop.Word.WdGoToItem]::wdGoToPage,
                     [Microsoft.Office.Interop.Word.WdGoToDirection]::wdGoToAbsolute,
                     1 #page number
                     )
$doc.Bookmarks.Item("\page").range.select()
$word.Selection.Collapse([Microsoft.Office.Interop.Word.WdCollapseDirection]::wdCollapseEnd)
$word.Selection.InsertNewPage()
[Void]$word.Selection.GoTo([Microsoft.Office.Interop.Word.WdGoToItem]::wdGoToPage,
                 [Microsoft.Office.Interop.Word.WdGoToDirection]::wdGoToAbsolute,
                 2 #page number
                 )