I built a script that converts .doc
files to .docx
.
I have a problem that when the .doc
file is password-protected, I can't access it and then the script hangs.
I am looking for a way to check if the file has a password before I open it.
I using Documents.Open
method to open the file.
If your script hangs on opening the document, the approach outlined in this question might help, only that in PowerShell you'd use a try..catch
block instead of On Error Resume Next
:
$filename = "C:\path\to\your.doc"
$wd = New-Object -COM "Word.Application"
try {
$doc = $wd.Documents.Open($filename, $null, $null, $null, "")
} catch {
Write-Host "$filename is password-protected!"
}
If you can open the file, but the content is protected, you can determine it like this:
if ( $doc.ProtectionType -ne -1 ) {
Write-Host ($doc.Name + " is password-protected.")
$doc.Close()
}
If none of these work you may have to resort to the method described in this answer. Rough translation to PowerShell (of those parts that detect encrypted documents):
$bytes = [System.IO.File]::ReadAllBytes($filename)
$prefix = [System.Text.Encoding]::Default.GetString($bytes[1..2]);
if ($prefix -eq "ÐÏ") {
# DOC 2005
if ($bytes[0x20c] -eq 0x13) { $encrypted = $true }
# DOC/XLS 2007+
$start = [System.Text.Encoding]::Default.GetString($bytes[0..2000]).Replace("\0", " ")
if ($start -like "*E n c r y p t e d P a c k a g e") { $encrypted = $true }
}
There is a technique outlined here. Essentially, you supply a fake password which files without a password will ignore; then you error-trap the ones that do require a password, and can skip them.