如何检查单词文件是否有密码? [英] How to check if a word file has a password?
问题描述
我构建了一个将.doc
文件转换为.docx
的脚本.
I built a script that converts .doc
files to .docx
.
我遇到一个问题,当.doc
文件受密码保护时,我无法访问它,然后脚本挂起.
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.
我使用Documents.Open
方法打开文件.
推荐答案
如果脚本在打开文档时挂起,则中概述的方法这个问题可能有帮助,只有在PowerShell中您使用try..catch
块而不是On Error Resume Next
:
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()
}
如果这些方法都不起作用,您可能不得不求助于此答案中所述的方法.粗略翻译到PowerShell(用于检测加密文档的部分):
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 }
}
这篇关于如何检查单词文件是否有密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!