Owain Esau
Owain Esau

Reputation: 1922

Word bypass password protected files

PURPOSE

The script should iterate through each file in a folder, convert to .txt and upload text to Azure database

PROBLEM

Everything works fine up until it hits a password protected file, I just want to skip these files. I am running this on hundreds of thousands of documents and the script will pause if it hits a password protected file until you either enter the password or click Cancel.

SCRIPT

Write-Output "Processing: $($file)"
Try {
    $doc = $word.Documents.OpenNoRepairDialog($file)
}
Catch {

}

if ($doc) {
    $fileName = [io.path]::GetFileNameWithoutExtension($file)
    $fileName = $filename + ".txt"
    $doc.SaveAs("$env:TEMP\$fileName", [ref]$saveFormat)
    $doc.Close()


    $4ID = $fileName.split('-')[-1].replace(' ', '').replace(".txt", "")
    $text = Get-Content -raw "$env:TEMP\$fileName"
    $text = $text.replace("'", "")

    $query += "
    ('$text', $4ID),"
    Remove-Item -Force "$env:TEMP\$fileName"
}

SOLUTION

For anyone having the same issue, the solution was to pass a non empty string to the open call like so:

$wd.Documents.Open($file, $false, $falsel, $false, "ttt")

rather than

$wd.Documents.Open($file, $false, $falsel, $false, "")

Upvotes: 3

Views: 1638

Answers (1)

RoadRunner
RoadRunner

Reputation: 26335

Here is a demo script of indicating if a Word document is password protected in the current directory. If the file opening doesn't get triggered by the catch block, continue your logic in the try block.

$wd = New-Object -ComObject Word.Application

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$files = Get-ChildItem $dir -Include *.doc, *.docx -Recurse

foreach ($file in $files) {
    try {
        $doc = $wd.Documents.Open($file, $null, $null, $null, "")
    } catch {
        Write-Host "$file is password-protected!"
    }
}

You will need to integrate the rest of your logic if you choose this approach, but it shows the general idea of checking password protected files.

Upvotes: 6

Related Questions