Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - How to check if a word file has a password?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:pathoyour.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 "D?") {
  # DOC 2005
  if ($bytes[0x20c] -eq 0x13) { $encrypted = $true }

  # DOC/XLS 2007+
  $start = [System.Text.Encoding]::Default.GetString($bytes[0..2000]).Replace("", " ")
  if ($start -like "*E n c r y p t e d P a c k a g e") { $encrypted = $true }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...