Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Process multiple word docs (office 2010)

I am trying to write a PowerShell script to perform steps on multiple Word docs. I have Word 2010 installed on my machine, but I can't seem to get the script to open the docs. Here is the script

    $path = "C:\MyPath" 
    Add-Type -AssemblyName Microsoft.Office.Interop.Word  
    $wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse 
    $objWord = New-Object -ComObject "word.application"
    $objWord.visible = $false 
    foreach($wd in $wordFiles) 
    { 
    $doc = $objWord.documents.open($wd.fullname) 
    #InsertProcessingFunctionsHere 
    $doc.Save() 
    $objWord.Documents.Close() 
    } 
    $objWord.Quit()

I try and run this, and the error I get back from PowerShell is:

    Exception calling "Open" with "1" argument(s): "Command failed"
    At C:\Scripts\Process-WordDocs.ps1:10 char:31
    + $doc = $objWord.documents.open <<<< ($wd.fullname)
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : ComMethodTargetInvocation

    You cannot call a method on a null-valued expression.
    At C:\Scripts\Process-WordDocs.ps1:13 char:10
    + $doc.Save <<<< ()
        + CategoryInfo          : InvalidOperation: (Save:String) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull

    Exception calling "Close" with "0" argument(s): "This method or property is not available because a document window is not active."
    At C:\Scripts\Process-WordDocs.ps1:14 char:25
    + $objWord.Documents.Close <<<< ()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : ComMethodTargetInvocation

MSDN states that documents.open only requires 1 argument, and the rest are optional. However, a C# example I have seen on the net, showed passing a "ReadOnly: False" parameter to documents.open. Stepping through the script in the ISE Debugger, I can see $wd.fullname is there and points to a valid file, so I am completely unclear why it is not opening. At first, I thought this was because I was using a 64-bit version of the OS (32-bit version of Office), but attempting the script from a 32-bit PowerShell Session resulted in the same error. Anyone have any insight here as to why this may be happening, and how I can fix it? I would prefer all the processing to happen invisible to the user. Any help would be greatly appreciated. Thank you in advance for your time.

like image 394
user1389971 Avatar asked Oct 16 '25 19:10

user1389971


1 Answers

I think you want to close the document using $doc.close() instead of $objWord.Documents.Close()

like image 71
Andrew Avatar answered Oct 18 '25 12:10

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!