我對 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 代替,但不確定如何將其插入我的代碼中!
uj5u.com熱心網友回復:
$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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474174.html
