1

I am writing a function that is part of a much larger script that will take input from a web form, check to see if that user exists in either our AD or Linux systems, create the account if it doesn't, email the user when it's done, then create a Word document that we can print out and give them with their credentials (sans temp password), email address, and basic information about our IT services. I have been beating my head against the wall with the Word integration. There is almost ZERO Powershell documentation online for Word integration. I've been having to translate what I can from C# and VB and even half of that isn't even translateable. I've got it mostly working now but I'm having problems getting PS to put my text in the correct location in the Word template. I have a Word Template with 4 bookmarks where I am inserting the user's name, username, email address, and account expiration. The problem is, PS is placing all of the text at the same bookmark. I've found that if I put info in the script statically it will work (ie. $FillName.Text = 'John Doe') but if I use a variable it will just stick all of them at the first bookmark. Here is my code:

Function createWordDocument($fullname,$sam,$mailaddress,$Expiration)
{
     $word = New-Object -ComObject "Word.application"

     $doc = $word.Documents.add("C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\welcome2.dotx")         
     $FillName=$doc.Bookmarks.Item("Name").Range
     $FillName.Text="$fullname "         
     $FillUser=$doc.Bookmarks.Item("Username").Range
     $FillUser.Text="$sam"       
     $FillMail=$doc.Bookmarks.Item("Email").Range
     $FillMail.Text="$mailaddress"       
     $FillExpiration=$doc.Bookmarks.Item("Expiration").Range
     $FillExpiration.Text="$Expiration"          
     $file = "C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\test1.docx"
     $doc.SaveAs([ref]$file)

     $Word.Quit()


}

The function is receiving parameters that originated from a import-csv. $fullname, $sam and potentially $mailaddress have all been modified from their original inputs. #Expiration comes from the import-csv raw. Any help would be appreciated. This seems to be the most relevant info I could find and as far as I can tell I've got the same code, but It won't work for multiple bookmarks.

1
  • I'll write up an answer with more details, but I do something similar regularly and I have 2 words for you: Mail Merge ...if you aren't familiar with it, you may want to google it because it does what you want, and you can make PowerShell automate it. Answer coming shortly with details. Jun 24, 2014 at 22:05

2 Answers 2

1

Ok, like I suggested you can setup a Mail Merge base that you can use to create docs for people. It does mean that you would need to output your data to a CSV file, but that is pretty trivial.

Start by setting up a test CSV with the data that you want to include. For simplicity you may want to place it with the word doc that references it. We'll call it mailmerge.csv for now, but you can name it whatever you want. Looks like Name, UserName, Email, and Expiration are the fields you would want. You can use dummy data in those fields for the time being.

Then setup your mail merge in Word, and save it someplace. We'll call it Welcome3.docx, and stash it in the same place as your last doc. Then, once it's setup to reference your CSV file, and saved, you can launch Word, open the master document, and perform the merge, then just save the file, and away you go.

I'll just use a modified version of your function which will create the CSV from the parameters provided, open the merge doc, execute the merge, save the new file, and close word. Then it'll pass a FileInfo object back so you can use that to send the email, or whatever.

Function createWordDocument($fullname,$sam,$mailaddress,$Expiration)
{
     [PSCustomObject]@{Name=$fullname;Username=$sam;Email=$mailaddress;Expiration=$Expiration}|Export-Csv "C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\mailmerge.csv" -NoTypeInformation -Force
     $word = New-Object -ComObject "Word.application"

     $doc = $word.Documents.Open("C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\welcome3.dotx")
     $doc.MailMerge.Execute()
     $file = "C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\$fullname.docx"
     ($word.documents | ?{$_.Name -Match "Letters1"}).SaveAs([ref]$file)

     $Word.Quit()

     [System.IO.FileInfo]$file
}
1
  • This put me on the right path. I wound up using a mail merge but had some more difficulties. I'll put my final code and some comments in another post
    – phoenix79
    Jun 25, 2014 at 20:58
0

TheMadTechnician put me on the right track, but I had to do some tweaking. Here is what I wound up with:

Function createWordDocument($fullname)
{
     $word = New-Object -ComObject "Word.application"        
     $doc = $word.Documents.Add("C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\welcome_letter.docx")       
     $doc.MailMerge.Execute()    
     $file = "C:\Users\smiths\Documents\Powershell Scripts\webformCreateUsers\$fullname.docx"
     ($word.documents | ?{$_.Name -Match "Letters1"}).SaveAs([ref]$file)
     $quitFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveOptions],"wdDoNotSaveChanges")
     $Word.Quit([ref]$quitformat)        
}

Instead of passing the arguments to the function, I had the main function create the mailmerge.csv file for me and just have the Word template connect to it. I'm still passing $fullname since that's what I'm naming the file in the end. The two major hiccups in the end were that everytime a mailmerge document file is opened, Word asks if you want to conect back to the source data. This means that when Powershell was trying to open it, Word was waiting for interaction and then PS would close it when it thought it was done. Of course, this meant that nothing got done. I found that there is a registry key that you must create to enable Word to skip the SQL Security check. for posterity's sake you must create a key here: HKCU\Software\Microsoft\Office\14.0\Word\Options\ called SQLSecurityCheck with a DWORD value of 0. That allowed Word to properly open the template and manipulate the files. The last bit of trouble that I had was that Word was wanting to re-save the original file each time it ran and would leave a dialogue box open which would leave Word open and in memory. The last 2 lines force word to close without saving.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.