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



我是一个很新的Powershell,一直在撞我的头在这个一段时间,希望有人能指出我对哪里我错了。我试图使用Powershell从一个文件夹中的多个。docx文件中删除打开密码。我可以让它将密码更改为其他东西但不能让它完全删除粗体中的部分下面是我绊倒的地方,错误代码细节在底部,感谢任何帮助!

$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://learn.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()