I'd like to make a Microsoft Word document be set with a password for opening the document. When I try to run the following code in Powershell, the script will hang once I enter the desired password.
This script will be run in Kaseya to help automate protecting Word documents. I've tried both modifying the Document.Password
property and using the Document.Protect
method and they both will hang the script.
$path = Read-Host("Specify path to word document")
Write-Host "Creating Word application object..."
$wordAppObj = New-Object -ComObject Word.Application
Write-Host "Creating Word document object..."
$wordDocObj = $wordAppObj.Documents.Open($path)
# Write-Host "Activating Word document object..."
# $wordDocObj.Activate
Write-Host "Setting password..."
$securePass = Read-Host("Set password as") -AsSecureString
$password = ConvertFrom-SecureString $securePass
# $wordDocObj.Protect(3, $true, $password)
$wordDocObj.Password = $password
Write-Host "Saving Word document object..."
$wordDocObj.Save
Write-Host "Closing the Word document..."
$wordDocObj.Close
Write-Host "Closing Word..."
$wordAppObj.Application.Quit()
I expect the script to run through and protect the file, but the script will hang and an instance of Microsoft Word will be running in the background taking up about 6-9% of the CPU. Nothing will happen to the file or in the script. There are no error messages that pop up.
UPDATE: As suggested, I added $wordAppObj.Visible = $true
to the script to see if there were any pop-ups that happened during the execution of the script. Unfortunately, I didn't see any. I believe the script may be hanging when it prompts the user to re-enter the password. This happens when I use Word to encrypt a document with a password. Is there any way to fill this field in from Powershell?
I have developed a program in C# with the Microsoft Interop reference for Word. This program worked for me. At this point, I believe that this kind of thing cannot be done from Powershell and I would advise that anyone trying to do this seek another way to get this done. I think Powershell simply doesn't support modifying the password field of a document.