Insert a Page Break in a Word Document using PowerShell
I got this idea from “dmtelf” who posted a comment on a previous post I wrote regarding Microsoft Word and PowerShell. I ran through a few tests and this is the result.
First, lets Insert a Page Break after every Paragraph in a Word Document. The script will insert a Page break after each Paragraph. I’ve created a sample Word Document that has 5 Lorem Ipsum paragraphs.
Connecting to the Word Document is done through the Word.Application -Com Object. Then we use the Open() method to connect to our Word Document. Next we create a New Variable holding every Paragraph in the Word Document, Loop through the Paragraphs and set the PageBreak to -1. This sets a Pagebreak for each new Paragraph.
function Insert-PageBreak ([string]$File) {
$Word = New-Object -Com Word.Application
$OpenDoc = $Word.Documents.Open($File)
$Paragraphs = $OpenDoc.Paragraphs
$Paragraphs | ForEach {
$_.PageBreakBefore = -1
}
$OpenDoc.Close()
}
Running the Function on a Word Document inserts a PageBreak after each Paragraph as shown below:
PS > Insert-PageBreak "C:\Documents\Lorem Ipsum.doc"
Now, what if i want to insert a Pagebreak after a “Heading 1″ instead of a paragraph, when I write Word documents i sometimes get a little sloppy and push “enter” a little too often so that i get lots of unwanted paragraphs.
We can solve this with a simple if statement as shown below.
function Insert-PageBreak ([string]$File) {
$Word = New-Object -Com Word.Application
$OpenDoc = $Word.Documents.Open($File)
$Paragraphs = $OpenDoc.Paragraphs
$Paragraphs | ForEach {
$_.Style.NameLocal
if ($_.Style.NameLocal -match "Heading 1") {
$_.PageBreakBefore = -1
}
}
$OpenDoc.Close()
}
Running the Function on a Word Document containing “Heading 1″ sets the PageBreak for each New “Heading 1″
PS > Insert-PageBreak "C:\Documents\Lorem Ipsum.doc"
Note that if the Headings are not correctly inserted in the Word Document, it might screw things up a little in the Document, so take a backup before trying this at home
Lets replace the word “ring of fire” with “Chuck Norris RoundHouse Kick”
The function used is pretty straight forward. First setting up the variables required by the Execute() method and then connecting to the document that we want to manipulate.
So it’s basically 2 cells that I’m going to modify and then saving it into a new Excel File.
Connecting to Excel through PowerShell is done using the Excel.Application COM Object.
Below is a function that automates these steps. Just Change the $File Variable to your Template file instead.
