CharlesH
CharlesH

Reputation: 196

PowerShell Word Mail Merge Script

I have a script that used to work fine on older versions of Office but on 2010 is now failing to Mail Merge Documents correctly.

The interesting thing is that if I load the mail merge document (by double clicking) it then tells me its a mail merge document and needs to confirm its source data file. Which is all fine however this behaviour is not the same if I open via PS it simply loads as a normal document, the troublesome snippet of code is below:

if ($choice) {
    $word = New-Object -com "Word.Application"
    $template=$word.Documents.open("$template_path\$choice",$word.wdReadOnly)
    $word.ActiveDocument.Mailmerge.Execute()
    $template.close([ref]$word.wdDoNotSaveChanges)  
    $word.Visible = 'True'
}

I did come across a link that exampled this problem but I'm not an expert coder and the information went over my head a little bit, he stated this:

Sub OpenWord(fileName)
    Set Word = WScript.CreateObject("Word.Application")
    Word.Visible = True
    Set doc = Word.Documents.Open(fileName)
End Sub


I have seen some issues with such code if the word document has a mail merge data source associated with it and you try to execute it (see Word Mail Merge).
doc.MailMerge.Execute True

Trying to execute the mail merge generates a ‘This method or property is not available because the document is not a mail merge main document.’ But I know this is wrong because double clicking on the file reveals a data source associated with the document. Another way to open a word document and circumvent this issue is to use the run command such as:

Sub OpenWord(fileName)
    Set WshShell = WSCript.CreateObject("WScript.Shell")
    WshShell.Run fileName, 8, False
End Sub

Could someone explain how I can take this information and apply it to my powershell script?

Upvotes: 3

Views: 5276

Answers (1)

user1379931
user1379931

Reputation:

Ensure that the windows registry setting "SQLSecurityCheck" described in support.microsoft.com/kb/825765 have been set up for Word 2010 as well as the older versions of Word.

Upvotes: 0

Related Questions