dwwilson66
dwwilson66

Reputation: 7066

How does Powershell access Word and Word objects?

I am using the following script to convery a directory full of txt and rtf documents to Word documents.

$global:word = new-object -comobject word.application 
$word.Visible = $False 
$srcfiles = \\Path\to\files
$savepath = \\Path\to\docfiles
$saveFormatDoc = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], 0); 

function saveas-document ($docs) {             
    "Opening $($docs.FullName)"
    $opendoc = $word.documents.open($docs.FullName)

    $savepath = "$docPath$($docs.BaseName)"
    "Converting to $savepath.doc"    
    $opendoc.saveas([ref]"$savepath", [ref]$saveFormatDoc)
}

ForEach ($doc in $srcfiles) { 
saveas-document -docs $doc
}

With the way it's coded right now, I think it's opening a new instance of Word, opening the rtf/txt document in Word, saving as a Word doc and repeating. I'm not quitting Word (unless there's an implicit $word.quit() in there somewhere. I fear I'm killing performance with multiple instances of Word, but don't know if that's a concern I need to have or not.

What's a more efficient way of coding this to open a single instance of Word for document handling, and what's the syntax for opening Word as an application rather than opening a series of documents that launch the Application based on their file associations (which is what I fear it's doing now)?

Upvotes: 0

Views: 852

Answers (2)

Colyn1337
Colyn1337

Reputation: 1723

Your New-Object is outside your loop so you're only using the one instance. When you assign the New-Object to a variable (the object reference) and reuse it, that same object get's reused unless you destroy it or create another. Your script, in it's current form, is not creating a new object for each $doc in $srcfiles as you might be thinking.

Upvotes: 2

Austin T French
Austin T French

Reputation: 5131

With COM Objects, you are not launching the application, or dozens of them. You are opening a binary interface to libraries

You don't need or want to open a Com Object over and over, as that would cause a delay and performance hit.

You should close the Com-Object ($word.Quit()) at the end of the script though.

Upvotes: 1

Related Questions