0

Ok, here is the problem, randomly the LoadFiles option doesn't like a certain input file and produces an error. This error is always a terminating error and I cannot figure out any way to get it to continue. Any Ideas?

Function ProcessImage {
    Param(
        [Parameter(ValueFromPipeline=$true)]
        [System.IO.FileInfo]$File
    )

    If ($Excluded_Owners -notcontains $(get-acl -path $File.FullName).owner) {                                         #Check owner of the file and compare it to list of blacklisted file owners.
        Try{
            $Image = New-Object -ComObject Wia.ImageFile
            $Image.LoadFile($File.fullname)
        } Catch{
            LogWriter -OutPut "File Failed Process File in WIA - `"$($File.fullname)`""
            Write-Error $_.Exception.Message
            continue
        }

        If($Image.width -gt $PictureMinWidth -or $Image.height -gt $PictureMinHeight) {                                #Check image dimensions.
            IF ($Script:Copy) {
                $CopyTryCount = 0
                While ((Test-Path -Path "$CopyDir\$($Script:MF_ImagesCopied + 1)$($File.extension)" -PathType Leaf) -EQ $False -AND $CopyTryCount -le 3) {           #After the script says the picture was copied without error, verify it indeed was.
                    $CopyTryCount++
                    Try {
                        Copy-Item -Path $File.FullName -Destination "$CopyDir\$($Script:MF_ImagesCopied + 1)$($File.extension)" -Force                                    #If the picture meets all requirements, attempt to copy the image.
                    } Catch {
                        LogWriter -Status "Failure" -Output "File Failed to Copy (Attempt $CopyTryCount) - `"$($File.fullname)`""
                    }
                }
                IF (Test-Path -Path "$CopyDir\$($Script:MF_ImagesCopied + 1)$($File.extension)" -PathType Leaf) {                                         #Check the CopyDir directory for the image.
                    LogWriter -Status "Success" -Output "File Successfully Copied - `"$($File.fullname)`""             #If the image was copied successfully, log that.
                    [Int]$Script:MF_ImagesCopied += 1
                    $Temp_ProcessImage_Success=$True
                } Else {
                    LogWriter -Status "Failure" -Output "File Failed to Copy after 3 tries - `"$($File.fullname)`""    #If the image was not copied successfully, log that.
                    [Int]$Script:MF_ImagesFailed+= 1
                }
            }
        } Else {
            LogWriter -Status "Skipped" -Output "Incorrect Dimensions - `"$($File.fullname)`""
            [Int]$Script:MF_ImagesSkipped += 1
        }
    } Else {
        LogWriter -Status "Skipped" -Output "Excluded Owner - `"$($File.fullname)`""
        [Int]$Script:MF_ImagesSkipped += 1
    }
}#End ProcessImage

This is the troublesome error.

ProcessImage : Exception calling "LoadFile" with "1" argument(s): "The segment is already disca rded and cannot be locked. " At L:\MediaFinder.ps1:400 char:83 + If ($Images -AND $ImageFileTypes -contains "*"+$.Extension) {ProcessImage <<<< $} + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ProcessImage

1 Answer 1

1

You have caught the terminating error in a catch block and turned it into a non-terminating error. That's the first important step. BTW the continue in your catch block may also be causing premature termination. Continue is meant to be used with loops and with the Trap statement. Remove it and replace with a return statement.

The reason your function doesn't process any other files is that it isn't written quite right. So the second step is to put your script in a process block so it can process each $File object passed down the pipeline e.g.:

function ProcessImage {
    param(
        [Parameter(ValueFromPipeline=$true)]
        $File
    )

    process {
        try {
            if ($file -eq 'foo') {
                throw 'kaboom'
            } 
            else {
                "Processing $file"
            }
        } 
        catch {
            Write-Error $_
            return # can't continue - don't have valid file obj
        }
        "Still processing $file" 
    }
}

And if I run the above with these parameters, you can see that it processes objects after the one that throws a terminating error:

C:\PS> 'bar','foo','baz' | ProcessImage
Processing bar
Still processing bar
ProcessImage : kaboom
At line:1 char:21
+ 'bar','foo','baz' | ProcessImage
+                     ~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ProcessImage

Processing baz
Still processing baz
2
  • I simply added changed continue with return and the script runs flawlessly now, thank you. As for the "Process" block, what advantages does using a process block have? I have seen it in a number of different scripts but I am not sure I see an advantage of using it.
    – Nick W.
    Sep 14, 2014 at 6:51
  • 2
    The process block is required if you want to process more than the just the last pipeline object when your function is used in a pipeline (like my example usage above demonstrates). When you don't specify a begin/process/end block, PowerShell just puts all your script into an end block for you. That script block only gets executed once as the pipeline is finishing executing. If you want your command to be called for each object in the pipeline then you need to put the relevant code inside a process {} block. Your $File parameter inside that block will be updated for each new object.
    – Keith Hill
    Sep 14, 2014 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.