使用 Powershell 从 .Docx 文件中删除密码

Removing passwords from .Docx files using Powershell

我是 Powershell 的新手,一段时间以来一直在努力解决这个问题,希望有人能指出我出错的地方。我正在尝试使用 Powershell 从文件夹中的多个 .docx 文件中删除打开密码。我可以将密码更改为其他密码但无法将其完全删除,下面 Bold 中的部分是我被绊倒的地方,错误代码详细信息在底部,感谢任何帮助!

$path = ("FilePath")
$passwd = ("CurrentPassword")
$counter=1
$WordObj = New-Object -ComObject Word.Application
foreach ($file in $count=Get-ChildItem $path -Filter \*.docx) { 
  $WordObj.Visible = $true
  $WordDoc = $[WordObj.Documents.Open](https://WordObj.Documents.Open) 
  ($file.FullName, $null, $false, $null, $passwd)
  $WordDoc.Activate()
  $WordDoc.Password=$null
  $WordDoc.Close()
  Write-Host("Finished: "+$counter+" of "+$count.Length)
  $counter++
}

$WordObj.Application.Quit()
**Error details -** Object reference not set to an instance of an object. At line: 14 char: 5
\+$WordDoc.Password=$Null
\+Category info: Operations Stopped: (:) \[\], NullReferenceException
\+FullyQualifiedErrorId: System.NullReferenceException

我在别处得到了尝试使用 .unprotect 的答案,但不确定如何将其插入到我的代码中!

$path    = 'X:\TheFolderWhereTheProtectedDocumentsAre'
$passwd  = 'CurrentPassword'
$counter = 0
$WordObj = New-Object -ComObject Word.Application
$WordObj.Visible = $false

# get the .docx files. Make sure this is an array using @()
$documentFiles = @(Get-ChildItem -Path $path -Filter '*.docx' -File)
foreach ($file in $documentFiles) {
    try {
        # add password twice, first for the document, next for the documents template
        $WordDoc = $WordObj.Documents.Open($file.FullName, $null, $false, $null, $passwd, $passwd)
        $WordDoc.Activate()
        $WordDoc.Password = $null
        $WordDoc.Close(-1)  # wdSaveChanges, see https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveoptions
        $counter++
    }
    catch {
        Write-Warning "Could not open file $($file.FullName):`r`n$($_.Exception.Message)"
    }

}

Write-Host "Finished: $counter documents of $($documentFiles.Count)"

# quit Word and dispose of the used COM objects in memory
$WordObj.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WordDoc)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($WordObj)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()