Question:
I am looking to create a PowerShell script that will generate a Word document. It works as expected but when I run the script there is a space or a line break between “My Document: Title” and “Date: 01-07-2014”. The result looks like this:
1 2 3 4 |
My Document: Title Date: 01-07-2014 |
I want it to look like this:
1 2 3 |
My Document: Title Date: 01-07-2014 |
How can I write into this script a way to remove spaces within paragraphs? What I mean is, I want to set the paragraph spacing to single in PowerShell (not in Word as a default) By the way, if i do not add the $selection.TypeParagraph() before the “Date: $date”, the result looks like this:
1 2 |
My Document: TitleDate: 01-07-2014 |
As in, there is no carriage return at all. The goal is to have one carriage return but no space after that carriage return. Here is the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$date = get-date -format MM-dd-yyyy $filePath = "C:\users\myuser\file" [ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type] $word = New-Object -ComObject word.application $word.visible = $true $doc = $word.documents.add() $selection = $word.selection $selection.font.size = 14 $selection.font.bold = 1 $selection.typeText("My Document: Title") $selection.TypeParagraph() $selection.font.size = 11 $selection.typeText("Date: $date") $doc.saveas([ref] $filePath, [ref]$saveFormat::wdFormatDocument) |
Answer:
I think what you want is to change the Paragraph style from “Normal” to “No Spacing”.
The start of your code is the same:
1 2 3 4 5 6 7 8 |
$date = get-date -format MM-dd-yyyy $filePath = "C:\users\myuser\file" [ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type] $word = New-Object -ComObject word.application $word.visible = $true $doc = $word.documents.add() |
Then you want to change the paragraph style to “No Spacing”
1 2 3 4 |
$selection = $word.selection $selection.WholeStory $selection.Style = "No Spacing" |
And then you can carry on with the rest of your code:
1 2 3 4 5 6 7 8 9 10 |
$selection.font.size = 14 $selection.font.bold = 1 $selection.typeText("My Document: Title") $selection.TypeParagraph() $selection.font.size = 11 $selection.typeText("Date: $date") $doc.saveas([ref] $filePath, [ref]$saveFormat::wdFormatDocument) |