0

I've written a script to recursively loop through every directory, find word files and append "CONFIDENTIAL" to the footer. This worked fine until it came across an encrypted file which caused the script to hang and when I clicked cancel on the password prompt, it caused the script to crash. I've attempted to check if the document is encrypted before opening it but the prompt still opens which crashes the script. Is there a reliable way to check if the document is password protected that will work on .doc and .docx files? I've already tried using the code in the other thread and the first two methods don't work, the third method detects every file as encrypted because it throws an exception.

Current code:

$word = New-Object -ComObject Word.Application
$word.Visible = $false
$files = Get-ChildItem -Recurse C:\temp\FooterDocuments -include *.docx,*.doc
$restricted = "CONFIDENTIAL"
foreach ($file in $files) {
    $filename = $file.FullName
    Write-Host $filename
    try {
        $document = $word.Documents.Open($filename, $null, $null, $null, "")
        if($document.ProtectionType -ne -1) {
            $document.Close()
            Write-Host "$filename is encrypted"
            continue
        }
    } catch {
        Write-Host "$filename is encrypted"
        continue
    }
    foreach ($section in $document.Sections) {
        $footer = $section.Footers.Item(1)
        $footer.Range.Characters.Last.InsertAfter("`n" + $restricted)
    }
    $document.Save()
    $document.Close()
}
$word.Quit()
  • A search in the internet turns up all manner of "hits", including this one on Stack Overflow specific to PowerShell: https://stackoverflow.com/questions/17389528/how-to-check-if-a-word-file-has-a-password – Cindy Meister Jul 09 '18 at 15:08
  • 3
    Possible duplicate of [How to check if a word file has a password?](https://stackoverflow.com/questions/17389528/how-to-check-if-a-word-file-has-a-password) – Cindy Meister Jul 09 '18 at 15:08
  • I've figured out why the other answer's code was throwing an exception and I've proposed an edit to the answer to fix the solution. – David Cooke Jul 11 '18 at 06:17

1 Answers1

0

You can just use get-content.

$filelist = dir c:\tmp\*.docx 
foreach ($file in $filelist) {
    [pscustomobject]@{
        File = $file.FullName
        HasPassword = [bool]((get-content $file.FullName) -match "http://schemas.microsoft.com/office/2006/keyEncryptor/password" )
    }   
}

sample output:

File                                        HasPassword
----                                        -----------
C:\tmp\New Microsoft Word Document (2).docx       False
C:\tmp\New Microsoft Word Document.docx            True