Powershell function error handling

This topic contains 2 replies, has 2 voices, and was last updated by  Leonid Vinokur 1 year, 2 months ago.

  • Author
    Posts
  • #54776

    Leonid Vinokur
    Participant

    Hi,

    I wrote a powershell script which uses several functions. The script performs several actions and in case of error, calls the "cleanup" function. The cleanup function runs a few powershell commands to delete the created objects.
    Being lazy and all, I didn't want to test for the existence of the objects before deleting them. The function is expected to try and delete the objects and in case the object does not exist – move on to the next delete command.

    Issue: once an error is encountered that an object does not exist, the function breaks, but the script does not. Meaning instead of error and cleanup we get a mess of a work half done. I did a debug on the script and clearly saw that once an error is encountered, the function exits and script resumes from the same point that called the function. By the way, same behavior in every -errorAction I tried.
    Ended up wrapping each command in "try/catch" blocks. It is an okay workaround, but I was wondering if I could force the function to continue till the end in case of error without "try/catch".

    Any input is appreciated.
    Leonid

  • #54786

    Matt Bloomfield
    Participant

    Can you provide code examples? I tried a quick test with files and it just gives an error and continues deleting.
    My example just creates 5 text files, removes 3.txt, then calls another function to delete files 1 to 5. All the files are deleted before returning to the calling function even though an error is received for 3.txt

    
    1..5 | foreach {New-Item -ItemType File -Path E:\__Temp\test\"$_.txt"}
    Remove-Item E:\__Temp\test\3.txt
    
    function caller {
    
        cleanUp
        Write-Output "Finished!"
    
    }
    
    function cleanUp {
    
        1..5 | foreach {Write-Output "Deleting $_.txt";Remove-Item E:\__Temp\test\"$_.txt"}
    
    }
    
    caller
    
    
  • #54860

    Leonid Vinokur
    Participant

    Thanks for the reply.
    Unfortunately I cannot upload the code as it contains a lot of customer code.

    I did a code review and this is the process:

    1. The script defines functions "create" and "cleanup".
    2. The script calls the "create" function with a parameter of what to create. Lets say a file $_.txt. It uses a "try/catch" mechanism.
    3. Sometime the creation fails. In this case, we need to cleanup all the files created already. So the "catch" calls the "cleanup" function.
    4. In case something goes wrong in the "cleanup", the function exits and the script continues execution, which is something I'm trying to understand.
    I was not able to reproduce the issue in the test script you've uploaded, even after I've added the "try/catch". Trying on.

    Thanks,
    Leonid

You must be logged in to reply to this topic.