Powershell script to open and edit a protected MS Word document

Hi guys. I am working on a powershell script that would open up a protected word document (restrict edit mode ON)and edit the form fields. My thought was to unprotect the document via the script, fill the text fields, protect the document and then save it. Can anyone provide some info on the use of "unprotect/protect" through powershell script? I am using Word 2013. Here is a snippet:

$NewDocName = "C:\some-path-to-newdoc.docx"
$DocTemplate = "C:\some-path-to-masterWorddoc.docx"
$msWord = New-Object -Com Word.Application
$msWord.visible = $false
$wordDoc = $msWord.Documents.Open("$DocTemplate")
$wordDoc.Activate()
# attempt to unprotect the document here. empty password by default
$wordDoc.Unprotect()
$objRange = $wordDoc.Bookmarks.Item("lastname").Range
$objRange.Text = "wright"

$filename = $NewDocName
$wordDoc.SaveAs([REF]$filename)
$wordDoc.Close()
$msWord.Application.Quit()

When tried it shows an error that the document could not be edited as it is protected. So I believe the $wordDoc.Unprotect() fails to unprotect the document for editing the form fields.

When I manually made the document unprotected and then tried running the script, it works fine. The script edits the form fields.

I already posted this query in powershell forum, but I was suggested to contact here in Word forum.

Thanks in advance. Any help would be much appreciated

June 17th, 2015 9:59am

Hi,

This is the forum to discuss questions and feedback for Microsoft Excel, your issue is related to Power Shell, I recommend you post the question to the MSDN forum for Excel

http://social.msdn.microsoft.com/Forums/en-US/home?forum=exceldev&filter=alltypes&sort=lastpostdesc

The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.

George Zhao
TechNet Community Support

Free Windows Admin Tool Kit Click here and download it now
June 18th, 2015 9:55pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics