How to check if a word file has a password?

后端 未结 2 926
野趣味
野趣味 2020-12-20 08:48

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 a

相关标签:
2条回答
  • 2020-12-20 09:17

    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 }
    }
    
    0 讨论(0)
  • 2020-12-20 09:35

    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.

    0 讨论(0)
提交回复
热议问题