Reputation: 23
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
}
}
Upvotes: 1
Views: 1618
Reputation: 174485
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
}
}
Upvotes: 1