1

I'm working on a script to identify password protected pdf files in a folder. If the pdf is password protected then it will move the folder and all files and sub folders to another folder. I can get the script to work correctly with a copy but it appears the streamreader that is reading the files for "Encrypt" is locking the files preventing me from moving the files. I've been trying to work on a way to close streamreader but so far nothing has worked. Any help would be greatly appreciated.

$Source = 'sourcefolder'
$Dest = 'Destinationfolder'
        
Get-ChildItem -Path $Source -Directory |
ForEach-Object {
    If (Get-ChildItem -Path $_.FullName -filter *.pdf | where { 
            $_.OpenText().ReadToEnd().Contains("Encrypt") -eq $true }) {
        
        Move-Item -Path $_.FullName -Destination $Dest -Force -Verbose
    }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206

1 Answers1

1

You need to dispose of the stream reader before leaving the Where-Object block:

... |Where {
  try {
    ($reader = $_.OpenText()).ReadToEnd().Contains("Encrypt")
  }
  finally {
    if($reader){ $reader.Dispose() }
  }
}

In the context of your existing script:

Get-ChildItem -Path $Source -Directory | ForEach-Object {
  if (Get-ChildItem -Path $_.FullName -filter *.pdf | Where-Object { 
      try {
        ($reader = $_.OpenText()).ReadToEnd().Contains("Encrypt")
      }
      finally {
        if ($reader) { $reader.Dispose() }
      }
    }) {
        
    Move-Item -Path $_.FullName -Destination $Dest -Force -Verbose
  }
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • I'm having trouble placing the closing ) for the if statement. – Michael Moore Oct 06 '21 at 17:48
  • Get-ChildItem -Path $Source -Directory | ForEach-Object{ If (Get-ChildItem -Path $_.FullName -filter *.pdf | where { try{ ($reader = $_.OpenText()).ReadToEnd().Contains("Encrypt") } finally { if ($reader){ $reader.Dispose() } }} Move-Item -Path $_.FullName -Destination $Dest -Force -Verbose } – Michael Moore Oct 06 '21 at 17:49
  • @MichaelMoore I've updated the answer with the example in the full context. I'd also strongly suggest using an editor with proper syntactic highlighting (the PowerShell extension for vscode is very nice), if should make it easier to spot :) – Mathias R. Jessen Oct 06 '21 at 17:54
  • That worked, thank you very much! – Michael Moore Oct 06 '21 at 18:39