Powershell word header replace - powershell

I want to replace header in word document.
$pth = "d:\test\test.docx"
$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open($pth)
$objSelection = $objWord.Selection
$Section = $objDoc.Sections.Item(1)
$header = $Section.Headers.Item(1)
This return me a plain text:
Write-Host $header.Range.Text
But my header have an image and table. Can i replace string in header without destroying header? I replace strings in word document and works great. My only problem is header.
Link to example Word document header below.
http://zapodaj.net/223c522426648.png.html

Try this:
$replaceWith = "New Text !"
$replace = [Microsoft.Office.Interop.Word.WdReplace]::wdReplaceAll
$findWrap = [Microsoft.Office.Interop.Word.WdFindWrap]::wdFindContinue
$find = $header.Range.find
$find.Execute($header.Range.Text,
$false, #match case
$false, #match whole word
$false, #match wildcards
$false, #match soundslike
$false, #match all word forms
$true, #forward
$findWrap,
$null, #format
$replaceWith,
$replace)
The pictures and other tables, should remain untouched.

I don't know solution in powershell but I use VBA runed from powershell.
// code is changed so if it don't work let me know
$objWord = New-Object -ComObject word.application
$objWord.Visible = $True # don't have to be true
$pathToFile = "d:\Delivery_Templates\filename.docx" #path to your file
$objDoc = $objWord.Documents.Open(pathToFile )
$objSelection = $objWord.Selection
$objWord.Run('myReplace', [ref] $currentVersion); # myReplace - macro name, currentVersion - macro parameter

Related

How to set parameters for SaveAs() dialog in Word.Application?

I want to save a Word document as PDF from a PowerShell script.
The following code works for me.
$Word = New-Object -ComObject Word.Application
$Doc = $Word.Documents.Open("C:\TEMP\WORD.DOCX")
$Name = ($Doc.Fullname).Replace("DOCX", "PDF")
$result = $Doc.SaveAs([ref] $Name, [ref] 17)
$Doc.Close()
echo "Saved to $Name"
The produced PDF is a PDF/A though.
When I save the document manually then I can set the option "PDF/A compliant" in a dialog which pops up.
How can I change this format specific option via PowerShell?
The pictures explain perhaps better what I'm trying.
The only way I know of is by using the ExportAsFixedFormat function instead of SaveAs.
$Word = New-Object -ComObject Word.Application
$Doc = $Word.Documents.Open("C:\TEMP\WORD.DOCX")
$Name = [System.IO.Path]::ChangeExtension($Doc.Fullname, "PDF")
# Use ExportAsFixedFormat function.
# See: https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
# Parameters:
# OutputFileName, ExportFormat, OpenAfterExport, OptimizeFor, Range, From
# To, Item, IncludeDocProps, KeepIRM, CreateBookmarks, DocStructureTags
# BitmapMissingFonts, UseISO19005_1
# The last parameter 'UseISO19005_1' saves as PDF/A Compliant
$result = $Doc.ExportAsFixedFormat(
$Name,
[Microsoft.Office.Interop.Word.WdExportFormat]::wdExportFormatPDF,
$false,
[Microsoft.Office.Interop.Word.WdExportOptimizeFor]::wdExportOptimizeForOnScreen,
[Microsoft.Office.Interop.Word.WdExportRange]::wdExportAllDocument,
0,
0,
[Microsoft.Office.Interop.Word.WdExportItem]::wdExportDocumentContent,
$true,
$true,
[Microsoft.Office.Interop.Word.WdExportCreateBookmarks]::wdExportCreateWordBookmarks,
$true,
$false,
$true
)
$Doc.Close()
# clean up Com object after use
$Word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Returning Word search results using Powershell

I would like to extract formatting information from Word documents with PowerShell. Using Word you can search formatted pieces of texts. This way Word highlights the parts satisfying the criterion (e.g. green underlined text). With this one I can find italic text in PowerShell as well:
$objWord = New-Object -Com Word.Application
$myWordFile = 'C:\My\Word\File.docx'
$objDocument = $objWord.Documents.Open($myWordFile)
$objDocument.Paragraphs[0].Range.Find.Font.Italic = $true
$objDocument.Paragraphs[0].Range.Find.Execute()
However, I'm curious about the italic text itself, a similar thing as the content of the $matches for -match.
Here is an example of what you are trying to do …
This is find and replace, so, ignore that replace part if that is not your end goal - it is also find words and then applying italics, but the same approach can be used to just find all italicized words.
$application = New-Object -comobject word.application
$application.visible = $true
$document = $application.documents.open("C:fsoTest.docx")
$selection = $application.Selection
$words = "exchange","sql"
$matchCase = $false
$matchWholeWord = $true
$matchWildCards = $false
$matchSoundsLike = $false
$matchAllWordForms = $false
$forward = $true
$wrap = 1
$format = $true
$replace = 2
Foreach ($word in $words)
{
$findText = $word
$replaceWith = $word
$selection.find.replacement.font.italic = $true
$exeRTN = $selection.find.execute($findText,$matchCase,
$matchWholeWord,$matchWIldCards,$matchSoundsLike,
$matchAllWordForms,$forward,$wrap,$format,$replaceWith,
$replace)
}
… as documented here:
Hey, Scripting Guy! How Can I Italicize Specific Words in a Microsoft Word Document?

Replace Multiple words in MSWord using Powershell

I am trying to use powershell to replace multiple lines in a word document without having to save and close after every change. right now I have:
$objWord = New-Object -comobject Word.Application
function findAndReplace
{
$objDoc = $objWord.Documents.Open("C:\temp\test.docx")
$objWord.Visible = $false
$objSelection = $objWord.Selection
$a = $objSelection.Find.Execute($FindText, $false, $true, $False, $False, $False, $true, 1, $False, $ReplaceWith)
$objDoc.Save()
$objDoc.close()
}
############DEVICE DETAILS#############
$FindText = "USERID"
$ReplaceWith = $AssociateIDnum
findAndReplace
$FindText = "CONTACTNUMBER"
$ReplaceWith = $Phone
findAndReplace
Using this, I made the function that runs those commands, and I change the $findtext and $replacetext on each instance of a new word, then run the function each time.
With this method, the Word Doc opens and closes nearly 25 times to write each new word replacement.
Is there a way I can make a function or loop to make it change the $findtext
and $replacewith variable each time?
I am relatively new to powershell but I have been learning some of it on my own.
Try using a list of objects as a parameter to the function, something like that :
$objWord = New-Object -comobject Word.Application
function findAndReplace ($todoObjs)
{
$objDoc = $objWord.Documents.Open("C:\temp\test.docx")
$objWord.Visible = $false
$objSelection = $objWord.Selection
foreach ($todoObj in $todoObjs)
{
$a = $objSelection.Find.Execute($($todoObj.FIND), $false, $true, $False, $False, $False, $true, 1, $False, $($todoObj.REPLACE))
}
$objDoc.Save()
$objDoc.close()
}
############DEVICE DETAILS#############
$todo = #"
FIND,REPLACE
toto,titi
tutu,tata
"#
$todoObjs = ConvertFrom-Csv $todo
findAndReplace $todoObjs

Powershell - Trim word document

I have a word document, that I read with the following code:
$objWord = New-Object -Com Word.Application
$objWord.Visible = $false
$objDocument = $objWord.Documents.Open($Formularpath, $false, $true)
$documenttext = $objDocument.wordopenxml
Now I have my document, but there is alot of text I don't need. How can I cut the text, e.g. until 1 specific word? I know split(';') but I will need a whole word...

How can I create a MS Word document in PowerShell and set the paragraph/line spacing to none?

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:
My Document: Title
Date: 01-07-2014
I want it to look like this:
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:
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.
$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)
I think what you want is to change the Paragraph style from "Normal" to "No Spacing".
The start of your code is the same:
$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"
$selection = $word.selection
$selection.WholeStory
$selection.Style = "No Spacing"
And then you can carry on with the rest of your code:
$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)