Columns Page Layout in Word with Powershell - powershell

I'm creating a word document with Powershell and I need to create a two-column column similar to the GUI method shown in the screen shot below:
I've researched other websites that explain basic Powershell Word objects, properties and methods, such as this one. However, there seems to be a lot more functionality that is "hidden" deep in the pages and pages of properties and methods. I'm looking to create a two-column column in my word doc. Here is the code I used to create the document and write to it:
$fileName = 'C:\template.docx'
$word = New-Object -Com Word.Application
$word.Visible = $true
$document = $word.Documents.Open($fileName)
$selection = $word.Selection
$text = "Test Text."
$selection.TypeText($text)
$document.SaveAs($fileName)
$document.Close()
$word.Quit()
$word = $null

Having worked with Excel ComObjects, it's not the easiest to figure out how to make it work with PowerShell.
You're missing this line:
$selection.PageSetup.TextColumns.SetCount(2)
How to get there?
Check the Word Interop Com Object MSDN page
It's probably the PageSetup object we're interesting in (because in the GUI the two columns appear under Layout > Page Setup > Columns)
Googling "word com object pagesetup" leds to a better MSDN documentation page that lists the properties
Repeat this process for TextColumns - it has the methods in the "Remarks" but I prefer to a doc page which lists the members
Finally, finding the SetCount method.
Hopefully this helps you to figure out how to navigate the Word ComObject document in future. The examples are in VBA or C# at best and need to be translated to PowerShell.
$fileName = 'C:\Template.docx'
$binding = "System.Reflection.BindingFlags" -as [type]
$word = New-Object -Com Word.Application
$word.Visible = $true
$document = $word.Documents.Open($fileName)
$selection = $word.Selection
$text = "Test Text."
$selection.TypeText($text)
$selection.PageSetup.TextColumns.SetCount(2)
# check the GUI here.
# You will see the Layout > Page Setup > Columns > Two is selected
$document.SaveAs($fileName)
$document.Close()
$word.Quit()
$word = $null

Related

How add autocorrect entries with an hyperlink using powershell script

In MS Outlook, is there a way to automatically replace some words like Google, MSN, Facebook, etc (I have an exhausting list in a CSV file), by the hyperlink that redirects to correct website.
So basically when I type google it transforms it to a hyperlink.
My CSV file:
Word, URL
Facebook, https://facebook.com
MSN, https://msn.com
Google, https://google.com
What I have so far is a script that add to the object autocorrect entries a word and replaces it by another word not using a CSV but a word document. But I'm not able to replace it by an hyperlink. It causes an error saying that autocorrect entries accept only string format and not object (hyperlink).
Reference: Add formatted text to Word autocorrect via PowerShell
When I create manually via outlook an hyperlink and I add this hyperlink to autocorrect and I run the following PowerShell script I can't find this autocorrect entry:
(New-Object -ComObject word.application).AutoCorrect.Entries | where{$_.Value -like "*http*"}
I want to adapt this code coming from Use PowerShell to Add Bulk AutoCorrect Entries to Word
If someone has an idea on how to add a hyperlink to the autocorrect entries, I would be grateful.
Thanks!
I finally managed how to add autocorrect entries for both word and outlook.
I need to create a .docx file with 'X row' and '2 Columns', the first column contain the word that i want an autocorrect like 'google' and the second column the 'google' link.
$objWord = New-Object -Com Word.Application
$filename = 'C:\Users\id097109\Downloads\test3.docx'
$objDocument = $objWord.Documents.Open($filename)
$LETable = $objDocument.Tables.Item(1)
$LETableCols = $LETable.Columns.Count
$LETableRows = $LETable.Rows.Count
$entries = $objWord.AutoCorrect.entries
for($r=1; $r -le $LETableRows; $r++) {
$replace = $LETable.Cell($r,1).Range.Text
$replace = $replace.Substring(0,$replace.Length-2)
$withRange = $LETable.Cell($r,2).Range
$withRange.End = $withRange.End -1
# $with = $withRange.Text
Try {
$entries.AddRichText($replace, $withRange) | out-null
}
Catch [system.exception] {
Write-Host $_.Exception.ToString()
}
}
$objDocument.Close()
$objWord.Quit()
[gc]::collect()
[gc]::WaitForPendingFinalizers()
$rc = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($objWord)
This code allow to modify the file Normal.dotm that contains all the autocorrect to an object link (C:\Users{your user id}\AppData\Roaming\Microsoft\Templates)
But then to apply those change to Outlook you have delete the 'NormalEmail.dotm' and the copy/paste 'Normal.dotm' and the rename it to 'NormalEmail.dotm'
This is the script to avoid to do it manually :
$FileName='C:\Users\{your id}\AppData\Roaming\Microsoft\Templates\Normal.dotm'
$SaveTo='C:\Users\{your id}\AppData\Roaming\Microsoft\Templates\NormalEmail.dotm'
Remove-Item –path $SaveTo
$Word = New-Object –ComObject Word.Application
$Document=$Word.Documents.Open($Filename)
$Document.SaveAs($SaveTo)
$Document.Close

Creating powershell array

I am a newby to powershell and am trying to automate a complex process. I need to copy and paste a 3 columns of data from one spreadsheet to a second one which will then be exported to an SAP transaction line by line. In my search I found the link below that discusses using $arr1 = #(0) * 20 to create the array. I have two questions.
The first question is what is the (0) referencing?
Also, using this formula how do I reference the workbook, sheet, and column that I need to use to create the array? Any help would be greatly appreciated.
PowerShell array initialization
#() is an array literal (typically used to define empty or single element array)
You can also use list object (System.Collection.ArrayList), might be more convenient since it has dynamic size.
Below is a quick and dirty example with COM object (reads data from range into array list)
$excel= new-object -com excel.application
$excel.Visible = $false
$wb = $excel.workbooks.open("$home\Documents\book1.xlsx")
$ws = $wb.Sheets.Item("Sheet1")
$data = New-Object System.Collections.ArrayList
foreach ($i in 1..20){
$data.Add( (New-Object PSObject -Property #{A=$ws.Range("A$i").Value2; B=$ws.Range("B$i").Value2}) ) | Out-Null
}
Write-Output $data
$wb.Close()

iTextSharp text file to powershell in Landscape

I'm trying to convert a text file to PDF using powershell in landscape.
Currently using a iTextSharp that has got me to great place with text conversion to PDF however I'm not able to find anything to place it in landscape when the lines are added to create the PDF.
Here is what I'm currently using.
[System.Reflection.Assembly]::LoadFrom("I:\powershell\itextsharp.dll")
$doc = New-Object itextsharp.text.document
$stream = [IO.File]::OpenWrite("I:\powershell\test.pdf")
$writer = [itextsharp.text.pdf.PdfWriter]::GetInstance($doc, $stream)
$doc.Open()
[IO.File]::ReadAllLines("I:\powershell\test.txt") | foreach {
$line = New-Object itextsharp.text.Paragraph($_)
$doc.Add($line)
}
$doc.Close()
$stream.Close()
I have found some for C# and Java just nothing with powershell.
Tried this which did not work:
$doc = New-Object iTextSharp.text.Document([iTextSharp.text.PageSize]::LEGAL_LANDSCAPE)
Thank you so much.
D
Use the overloaded constructor that takes a Rectangle, which explicitly sets the page size:
$doc = New-Object itextsharp.text.document(New-Object itextsharp.text.Rectangle(792, 612));

Powershell Select-All from Word Doc

I want to open, then select all of the text from a word document, not any of the properties, formatting, etc. Ihave searched this site and googled it to no end. Basically similar to opening a Word doc and pressing Ctrl-A and assigning the result to a variable.
$word = New-Object -ComObject Word.Application
$word.visible = $True
$wordfilepath = "\\symphony1\powershell\Phones\Phone.docx"
$doc = $word.Documents.Open($wordfilepath)
????
$selection" >> $textfilepath
Basically a newbie question, but can anyone help?
Thanks.
This will probably suit your needs. It creates a new word object, opens your existing file, and pulls the text from it.
$filePath = <your file here>
$doc = New-Object -com word.application
$fileToOpen = $doc.Documents.Open("$filePath")
$text = $fileToOpen.Range().text
Be forewarned that it will strip out even very basic formatting features such as new lines. Here's a nice list of other range members and properties that you may find helpful.

Add AUTOTEXT to MS Word Document with Power Shell

I am working on a project where I need to add AUTOTEXT entries like the Page 1 of X listings to the header and footer of a Power Shell generated MS Word document. I have tried extracting ideas from the following C# examples, but I cannot seem to figure out how to make it work. I was curious if someone could share some code to help me with this.
A starting point. This function add page number to the footer of document passed as parameter ( used on word 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()
}
Another way is to create a Word Macro and execute from 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
The macro must be saved on normal.dot (normal.dotm for 2010 and above) to have it in all open documents.
In this way you can customize what you want in a word document and not just header/footer recording in a macro your actions in the docs.