Olive
Olive

Reputation: 33

Insert Object in a document

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:

The program used to create this object is..... that program is either not installed on your computer or it is not responding

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()

Upvotes: 3

Views: 1080

Answers (1)

G42
G42

Reputation: 10019

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()

Upvotes: 1

Related Questions