Delete file(s) after processing

Hi there, new poster here, hopefully I get everything right:

I have a lot of avi files stored on a NAS, mostly family vids and I’ve rewritten a simple script to use handbrake to do some transcoding, and then delete the file if the transcode reported success:

[blockquote]
$handbrake = “D:\Program Files\Handbrake\HandBrakeCLI.exe”
$files = @(Get-ChildItem . *.avi -Recurse)
foreach ($file in $files) {
$newFileName = $file.Fullname -replace ‘.avi$’,‘.mp4’
& $handbrake -i $file.FullName -o $newFileName --preset “Dave”
if ($LastExitCode -ne 0) { Write-Warning “Error converting $($file.FullName)” }
if ($LastExitCode -eq 0) {del $file.fullname}
}
[/blockquote]

You’d think the transcoding bit would be the hard bit, but that works fine, an equivalent quality mp4 is made in the same folder, however the delete fails, saying that I don’t have privileges to delete.

But if I literally highlight the command that just failed, copy paste and run it again it works fine.

Any thoughts?

The executable may still be running and have the file locked giving you a error 5, Access Denied. You also may be getting the last exit code of the previous command, not the one you are using, so it’s not really giving you accurate information. Check out System.Diagnostics.Process the below post and add your -i $file.FullName -o $newFileName –preset “Dave” in $pinfo.Arguments = “”

http://stackoverflow.com/questions/10262231/obtaining-exitcode-using-start-process-and-waitforexit-instead-of-wait

I was thinking along the same lines as Rob Simmers.

Another possibility is UAC getting in the way. Does the delete work if you execute the script in an elevated (run as Administrator) instance of PowerShell?

I changed it thusly:

[blockquote]{$handbrake = “D:\Program Files\Handbrake\HandBrakeCLI.exe”
$files = @(Get-ChildItem . *.avi -Recurse)
foreach ($file in $files) {
$newFileName = $file.Fullname -replace ‘.avi$’,‘.mp4’
& $handbrake -i $file.FullName -o $newFileName --preset “Dave”
if ($LastExitCode -eq 0) {del $file.fullname} else{ Write-Warning “Error converting $($file.FullName)” }
}
$files = @(Get-ChildItem . *.mkv -Recurse)
foreach ($file in $files) {
$newFileName = $file.Fullname -replace ‘.mkv$’,‘.mp4’
& $handbrake -i $file.FullName -o $newFileName --preset “Dave”
if ($LastExitCode -eq 0) {del $file.fullname} else{ Write-Warning “Error converting $($file.FullName)” }
}}[/blockquote]

And it decided to stop complaining. I’m not sure why because it was triggering the delete and there are no permissions issues, I didn’t change anything else, didn’t even close the powershell window between yesterday and today.

Thanks for the hints