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 }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…