Word绕过密码保护的文件

Owa*_*sau 2 powershell ms-word

目的

该脚本应遍历文件夹中的每个文件,转换为.txt并将文本上传到Azure数据库

问题

一切正常,直到找到受密码保护的文件为止,我只想跳过这些文件。我正在成千上万的文档上运行此脚本,如果脚本遇到受密码保护的文件,该脚本将暂停,直到您输入密码或单击“取消”为止。

脚本

Write-Output "Processing: $($file)"
Try {
    $doc = $word.Documents.OpenNoRepairDialog($file)
}
Catch {

}

if ($doc) {
    $fileName = [io.path]::GetFileNameWithoutExtension($file)
    $fileName = $filename + ".txt"
    $doc.SaveAs("$env:TEMP\$fileName", [ref]$saveFormat)
    $doc.Close()


    $4ID = $fileName.split('-')[-1].replace(' ', '').replace(".txt", "")
    $text = Get-Content -raw "$env:TEMP\$fileName"
    $text = $text.replace("'", "")

    $query += "
    ('$text', $4ID),"
    Remove-Item -Force "$env:TEMP\$fileName"
}
Run Code Online (Sandbox Code Playgroud)

对于有相同问题的任何人,解决方案是将一个非空字符串传递给open调用,如下所示:

$wd.Documents.Open($file, $false, $falsel, $false, "ttt")
Run Code Online (Sandbox Code Playgroud)

而不是

$wd.Documents.Open($file, $false, $falsel, $false, "")
Run Code Online (Sandbox Code Playgroud)

Roa*_*ner 5

这是一个演示脚本,用于指示Word文档在当前目录中是否受密码保护。如果文件打开没有被该catch块触发,请继续执行该块中的逻辑try

$wd = New-Object -ComObject Word.Application

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
$files = Get-ChildItem $dir -Include *.doc, *.docx -Recurse

foreach ($file in $files) {
    try {
        $doc = $wd.Documents.Open($file, $null, $null, $null, "")
    } catch {
        Write-Host "$file is password-protected!"
    }
}
Run Code Online (Sandbox Code Playgroud)

如果选择这种方法,则需要集成其余的逻辑,但是它显示了检查受密码保护的文件的一般思想。

  • 弄清楚了,我不得不将$ wd.Documents.Open($ file,$ null,$ null,$ null,“”)更改为$ wd.Documents.Open($ file,$ false,$ falsel,$ false, “ ttt”)不知道为什么,但是当使用空字符串作为密码时,单词正在打开。 (3认同)