0

I have a PowerShell script that looks for .doc files on a folder and subfolders, removes Read Only atribute, converts them to .docx and then moves the .doc file to Recycle Bin. The issue that I have is if the document is password protected it does not get converted to .docx hence it will get deleted. I need to exclude .doc Password Protected files from getting removed. How do I do that? Also i have the "Recycle" module installed. Here is the script:

$invocation = (Get-Variable MyInvocation).Value
$curr_path = Split-Path -parent $MyInvocation.MyCommand.Path
$doc_app = New-Object -ComObject Word.Application
Get-ChildItem -Path $curr_path -Recurse -Include *.doc | ForEach-Object {
$_.IsReadOnly=$false
Write-Host "Working on->" $_.FullName "..."
$document = $doc_app.Documents.OpenNoRepairDialog($_.FullName, $false, $false, $false, "ignorepass") $curr_path with $_.DirectoryName
$docx_filename = "$($_.DirectoryName)$($_.BaseName).docx"
$doc_app.DisplayAlerts = "wdAlertsNone"
$Format= [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatXMLDocument
$document.SaveAs($docx_filename, $Format)
$document.Close()
}
$doc_app.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc_app)
Get-ChildItem * -Include *.doc -Recurse | Remove-ItemSafely

I guess I have to use the -Exclude cmdled in the last line but i dont know the value for password protected file.

reape185
  • 1
  • 3
  • I think you should rename and not delete. Also, I think you should add some tests like ```if ($null -ne $document). Also, Demo it on files that have a password and see what your variables are getting. – dcaz Mar 14 '23 at 15:58
  • Have a look at [this answer](https://stackoverflow.com/a/17389732/9898643) – Theo Mar 14 '23 at 16:09
  • @Theo the script is not hanging trying to open the file. I already got around that by trying to input a fake password(Line 7 where it says ignorepass)so the script goes on error instead of waiting to input a password. – reape185 Mar 14 '23 at 20:25
  • Yes, that is why the linked answer uses `try{..} catch{..}` around that part to catch that and that is where you can skip processing the file – Theo Mar 14 '23 at 21:36
  • I'm not a PS expert so I don't know how to implement that into the code. An example would be appreciated – reape185 Mar 16 '23 at 13:20

0 Answers0