在文档中插入对象

时间:2017-06-29 14:39:14

标签: powershell ms-word

我尝试使用

将txt文件插入到文档中
$doc.selection.InlineShapes.AddOLEObject($txtFile)

但是当我运行它时,我收到一条错误消息:

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

可能是什么问题? TNX

代码:

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

1 个答案:

答案 0 :(得分:1)

使用它。请阅读代码内注释 查看the documentation for AddOLEObject了解详情。

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