Insert Object in a document - powershell

I try to insert a txt file to a document with
$doc.selection.InlineShapes.AddOLEObject($txtFile)
But when I run it I get an error message:
What could be the problem? tnx
The code:
$Global:path = "C:\Users\user\desktop"
$txtFile = New-Item $Global:path -Name TxtFile.txt
$docx = New-Object -ComObject Word.Application
$docx.Visible = $true
$docxFileName = $docx.Documents.add()
$docx.Selection.range.InsertAfter("hello")
$docx.Selection.InlineShapes.AddOLEObject($txtFile)
$docxFileName.SaveAs([ref]$Global:path,[ref]$SaveFormat::wdFormatDocument)
$docx.Quit()

Use this. Please read in-code comments.
Check out the documentation for AddOLEObject for more info.
$Global:path = "C:\Users\user\desktop"
# I've added the -Force flag. because if the file already exists,
# $txtFile will contain an error instead of the object you expect
# $Global:path > $path because you don't need to specify the scope when you use a variable.
$txtFile = New-Item $path -Name TxtFile.txt -Force
$docx = New-Object -ComObject Word.Application
$docx.Visible = $true
$docxFileName = $docx.Documents.add()
$docx.Selection.range.InsertAfter("hello")
# This line should contain an empty argument for ClassType, then the file path for FileName
$docx.Selection.InlineShapes.AddOLEObject("",$txtFile.FullName)
# again, $global:path is not required.
# you can specify a path and the docx extension will be added automagically
$docxFileName.SaveAs("$path\somefilename")
$docx.Quit()

Related

How can I change the colour of a particular word list within a docx file?

I am setting up a Powershell script that by passing the path to a directory, checks if any of the strings contained in an excel file appear in the doc or docx files in that directory. If so, the colour of that string has to be changed in the doc/docx file.
I've been messing around with Word's COM object for a while and haven't been able to get it to work.
Here is what I have so far
#Open a Folder Browser to select the folder to process
$fwd = New-Object System.Windows.Forms.FolderBrowserDialog
$null = $fwd.ShowDialog()
$path = $fwd.SelectedPath
$files = Get-ChildItem -Path $path| Where-Object -Property Extension -Match ".docx?"
#Load the excel file data to an arraylist object for late iteration
$forbiddenWordsFilePath = "<<Path_To_XLSX>>"
$forbiddenWords= Import-Excel -Path $forbiddenWordsFilePath
$WordDoc = New-Object -ComObject Word.Application
$WordDoc.visible=$false
#Iterate over the files contained on the folder
foreach ($file in $files) {
#Make a backup of the docx file previous to working with it
$fileBackupPath= $file.FullName+"_bck"
Copy-Item $file.FullName -Destination $fileBackupPath
#Opens the docx? file on background
$doc = $WordDoc.Documents.Open($file.FullName,[type]::Missing,$true)
$MatchCase = $false
$MatchWholeWorld = $true
$MatchWildcards = $false
$MatchSoundsLike = $false
$MatchAllWordForms = $false
$Forward = $false
$Wrap = 1
$Format = $true
$wdReplaceAll = 2
#Iterate over the words list and search for them on the docx file
foreach ($word in $forbiddenWords){
$Replace=$word.Search_Pattern
$doc.Content.Find.Execute($word.Search_Pattern, $MatchCase, $MatchWholeWorld, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $Replace, $wdReplaceAll)
}
}
#Clears any opened Microsoft Word process
$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$WordDoc)
[gc]::Collect()
[gc]::WaitForPendingFinalizers()
Remove-Variable WordDoc
It is clear to me that the colour change should be in the second foreach. But I am not able to find the code that allows me to do it.
I'm a bit of a novice in dealing with the Word COM object with Powershell.
The excel file has the following headers....
Control_Type Control Comments Search_Pattern
In case there are doubts about how to obtain the property "Search_word".

Powershell attached all file from folder

I need to email and attached all file from the folder but no include any sub-folder.
I am getting error
Cannot find an overload for "Add" and the argument count: "1".
At line:11 char:1
$emailMessage.Attachments.Add($getallfiles)
below is the powershell code.
$dir = "C:\Users\myid\Documents\comparsion\src\main\resources\excelfiles\Compare_Result_Files"
$getallfiles = Get-ChildItem "$dir\*.xlsx"
$emailSmtpServer = "mailhub-au.com"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "donotreply#company.com"
$emailMessage.To.Add( "myid#company.com" )
$emailMessage.Subject = "Selenium Report"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = "Test Summary Attached"
$emailMessage.Body = "$getallfiles"
$emailMessage.Attachments.Add($getallfiles)
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer ,$emailSmtpServerPort )
$SMTPClient.Send($emailMessage)`
You need to loop through the files and add one at a time.
Also the Attachments.Add() method requires the full file name, not a FileInfo object. See the docs
foreach ($file in $getallfiles) {
[void]$emailMessage.Attachments.Add($file.FulllName)
}
I would also suggest adding the -File switch to Get-ChildItem to ensure you only gather files, not folders.

Spellcheck content of Document in Powershell

I have added spell checking by reading contents of a file using powershell script?
This script does my job, but I want to check if there are any external packages or modules available for the same, since it would make the work easier.
$file = Get-ChildItem ./Code-Duplication/master.md
$Proofread_text = Get-Content $file.FullName
$Word = New-Object -COM Word.Application
$Document = $Word.Documents.Add()
$Textrange = $Document.Range(0)
#$english = FindLanguage("English (US)")
#$Textrange.LanguageID = $english.ID
$Textrange.InsertAfter($Proofread_text)
<#Handle misspelled words here#>
$file.Name
Write-Output "---------------"
foreach($spell_error in $textrange.SpellingErrors){
Write-Host $spell_error.Text
}
$Document.Close(0)
$Word.Quit()

How Do I Grab Text File Output and Pass Down Pipeline?

I've got an application that opens a winform and asks the user to input a PDF file. Because I can't read strings in PDF files easily, I need to convert it to a .txt. When the user clicks OK, the application does this.
The problem I'm having is now using the .txt file object and passing it to another command without knowing the name of it. When I try to pipe it to another command, it won't work because I don't have the path. I think this is because the output of conversion is the string "OK" and not the actual .txt file.
How can I convert the PDFs to text (I'm using Xpdf) and pass the converted file down the pipeline for further processing?
If the means I'm using is the problem, how can I accomplish this task another way?
Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$form.StartPosition = 'CenterScreen'
$button = New-Object System.Windows.Forms.Button
$form.Controls.Add($button)
$button.Text = 'Get file'
$button.Location = '10,10'
$button.Add_Click({
$ofd = New-Object system.windows.forms.Openfiledialog
$ofd.Filter = 'PDFs (*.pdf)|*.pdf'
$script:filename = 'Not found'
if ($ofd.ShowDialog() -eq 'Ok') {
$script:filename = $textbox.Text = $ofd.FileName
}
})
$buttonOK = New-Object System.Windows.Forms.Button
$form.Controls.Add($buttonOK)
$buttonOK.Text = 'Ok'
$buttonOK.Location = '10,40'
$buttonOK.DialogResult = 'OK'
$textbox = New-Object System.Windows.Forms.TextBox
$form.Controls.Add($textbox)
$textbox.Location = '100,10'
$textbox.Width += 50
$form.ShowDialog()
$output = & "C:\Users\eakinsa\Desktop\Style Guide Report\Includes\bin32\pdftotext" $filename
$output |
Get-Location -OutVariable textFile |
Select-String -Path $textFile -Pattern ed
Per Ansgar:
I amended the lines last few lines to, for now, maintain the default functionality of pdftotext where it creates the file in the same directory with the same name, as with his suggestion, I could easily replace .pdf with .txt on the end of the file path, thereby having the flexibility to pass the correct file path to subsequent functions. That made it so I was able to search the text file.
& "C:\users\eakinsa\Desktop\Style Guide Report\Includes\bin32\pdftotext" $filename
$pdf = Get-Item $filename
$textfile = $filename -replace '\.pdf$', '.txt'
Select-String -Path $textfile -Pattern ed
When you run pdftotext with just the input PDF as argument it creates the output text file in the same directory with the same basename and the extension txt.
& pdftotext C:\temp\foo.pdf # creates C:\temp\foo.txt
So you can build the text file path like this:
$pdf = Get-Item $filename
$textfile = Join-Path $pdf.DirectoryName ($pdf.BaseName + '.txt')
or like this:
$textfile = $filename -replace '\.pdf$', '.txt'
Alternatively you can tell pdftotext where to create the output file:
$textfile = 'C:\some\where\bar.txt'
& pdftotext $filename $textfile # creates C:\some\where\bar.txt

Powershell Script to change the font of word docs

Hi I am trying to create a script that changes the font of all word docs in a specific folder, I have managed to create one that changes the font for 1 document but cannot work out how to do this for all files my script is below
$Folder = Read-Host "Select Folder name"
$test = Test-Path C:\Users\andy.burton\Desktop\Layouts\$Folder\
$File = #
("0.bil","0.est","0.lbl","1.arm","1.bil","1.crd","1.env","1.est","1.frm","1.gp",
"1.hos","1.ins","1.lbl","1.lc","1.lmr","1.mls","1.NON","1.OP","1.pat","1.PRS
","1.rcl","1.rec","1.rmd","1.stm","10.pat","10.rec","11.pat","11.rec","12.pa
t","12.rec","13.pat","13.rec","14.PAT","14.rec","15.pat","16.pat","17.pat","18.pat","2.arm","2.bil","2.env","2.est","2.frm","2.gp","2.hos","2.ins","2.lbl","2.lc","2.lmr","2.mls","2.NON","2.pat","2.rcl","2.rec","2.rmd","2.stm","3.arm","3.bil","3.env","3.est","3.gp","3.hos","3.ins","3.lbl","3.lc","3.lmr","3.NON","3.pat","3.rec","3.rmd","3.STM","4.arm","4.bil","4.env","4.est","4.gp","4.hos","4.ins","4.lbl","4.lc","4.lmr","4.non","4.pat","4.rec","4.rmd","4.STM","5.arm","5.bil","5.env","5.est","5.gp","5.hos","5.ins","5.lbl","5.lc","5.lmr","5.non","5.pat","5.rec","5.rmd","6.bil","6.env","6.est","6.lbl","6.pat","6.rec","7.env","7.lbl","7.pat","7.rec","8.ENV","8.LBL","8.pat","8.rec","9.env","9.lbl","9.pat","9.rec","acchead.doc","address.lbl","apptreminder.email","apptreminder.sms","BMIBOOK.FRM","BUPA.OCR","clinicprint.rep","clinicprint2.rep","clinicprint2B.rep","clinicprint2C.rep","CLUB.BIL","Consent1.doc","consent2.doc","DEPOSIT.REC","ebs021.doc","ebs022.doc","EBS023.DOC","FConsent1.DOC","FEBS021.DOC","FEBS023.DOC","GP.OP","HCABOOK.FRM","InvCen.doc","InvFoot.doc","INVOICE.LBL","InvoiceGrid.doc","InvoiceGridNonVat.doc","InvoiceGridVAT.doc","InvoiceTotals.doc","InvoiceTotalsNonVAT.doc","InvoiceTotalsVAT.doc","J8160-95.LBL","J8160.LBL","J8162-95.LBL","J8162.LBL","J8163-95.LBL","J8163.LBL","J8165-95.LBL","J8165.LBL","J8360-95.LBL","J8360.LBL","J8362-95.LBL","J8362.LBL","J8363-95.LBL","J8363.LBL","J8365-95.LBL","J8365.LBL","J8560-95.LBL","J8560.LBL","J8562-95.LBL","J8562.LBL","J8563-95.LBL","J8563.LBL","J8565-95.LBL","J8565.LBL","L7160-95.LBL","L7160.LBL","L7161-95.LBL","L7161.LBL","L7162-95.LBL","L7162.LBL","L7163-95.LBL","L7163.LBL","L7164-95.LBL","L7164.LBL","L7165-95.LBL","L7165.LBL","L7166-95.LBL","L7166.LBL","L7167-95.LBL","L7167.LBL","L7168-95.LBL","L7168.LBL","L8162-95.LBL","letfoot.doc","lethead.doc","MC.BIL","NHS.PRS","NUFFBOOK.FRM","OPNOTE.OP","RecCen.doc","RECEIPT2.CC","ReceiptTotals.doc","recfoot.doc","remfoot.doc","shoulder1.jpg","shoulder2.jpg","TDL.FRM","TDL2.FRM","theatreprint.rep","VOUCHER2.CC")
if($test -eq $False) {
Copy-Item -Path 'C:\Users\andy.burton\desktop\Layouts\Arial 10' -Destination C:\Users\andy.burton\Desktop\Layouts\$Folder\ -Recurse
$file.ForEach({
$Word = New-Object -ComObject Word.Application
$Word.Visible = $False
$Doc = $word.Documents.Open()
$Selection = $word.Selection
$Doc.Select()
$Selection.Font.Name = "Calibri"
$Selection.Font.Size = 11
$Doc.Close()
$Word.Quit()
})
}
Else {Write-Warning "Folder Already Exists"}
You will want to use a Foreach loop and loop through your $File array. You may also want to rename $File to $Files
foreach($file in $Files)
{
# peform font change here
}
I had a need to change the font of a bunch of word documents in a share and the internet seems to point back to this post for results and references about changing the font of an entire word document using powershell. This code and answer did not show it very clearly so I contribute this code. This code gets the word documents in a folder that match the keywords you list in the $Files section, then changes the font to whatever you put in the $Selection.Font.Name = section. I modified the original code from this post to build this and I have already tested it on a local folder as well as a server share. Please let me know if it can be approved upon. For instance it would be nice to output to screen each file that is being changed.
$Folder = "\\SERVER\SHARE\FOLDER\"
$Files = Get-ChildItem -Path $Folder -Recurse -Include *misc*.doc, *.misc*.docx, *Misc*.docx, *Misc*.doc, *MISC.docx, *MISC*.doc, *test*.doc, *test*.docx, whatever.doc
foreach($File in $Files)
{
$Word = New-Object -ComObject Word.Application
$Word.Visible = $false
$Doc = $Word.Documents.Open($File.FullName)
$Selection = $Word.Selection
$Doc.Select()
$Selection.Font.Name = "Verdana Pro SemiBold"
$Doc.Close()
$Word.Quit()
}
Write-Warning "Finshed With Font Change"