Try-Catch not working like I expect RRS feed

  • Question

  • OK, so here's the code:

        try { $fileSearchResults = Get-ChildItem $divSearchDirectory -Filter $fileSearch -Recurse | Where-Object { ($_.Directory -notmatch 'archive') -and ($_.Name.Length -eq $nameTest) } }
        catch { 
            if ($Error[0].Exception.Message.Contains("Cannot find path")) {
                $_.Error = "Incorrect path"

    ...and here's the error message:

    Get-ChildItem : Cannot find path 'Z:\Site Visit Conversions\A10 Great Lakes\D' because it does not exist.
    At C:\Users\mcfarch\Scripts\File Opener.ps1:43 char:32
    + ... chResults = Get-ChildItem $divSearchDirectory -Filter $fileSearch -Re ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (Z:\Site Visit C...0 Great Lakes\D:String) [Get-ChildItem], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

    This is part of a ForEach-Object loop, so when it processes the list of documents, I'd really, really like it to chunk out an error attached to the particular list item so I can figure out why I'm seeing these error messages beyond "the file's not there." Specifically, I'm trying to figure out why the script can't find the files so I can either fix the file locations or adjust the script appropriately, but I can't do that without determining which specific files the script isn't finding, since the script does find a bunch of files, just not the ones that are producing the above error message. (Obviously)

    I've tried building similar scripts to run similar tests using the try-catch method, those work. This particular script isn't, and I'm tearing my hair out trying to figure out why. Any suggestions?

    Thursday, July 13, 2017 4:34 PM


All replies

  •  Get-ChildItem $divSearchDirectory -Filter $fileSearch -Recurse -ErrorAction Stop

    The only way to trap an exception.


    Thursday, July 13, 2017 4:38 PM
  • Unless things have changed, try catch block only works on Terminating Errors. If Get-ChildItem does not find a file the script does not "terminate", it displays the error and moves on.

    If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful. (99,108,97,121,109,97,110,50,64,110,121,99,97,112,46,114,114,46,99,111,109|%{[char]$_})-join''

    Thursday, July 13, 2017 4:38 PM
  • "Stop" works but it also terminates the pipeline so Try/Catch will not do what  is asked.

    To find all errors do this:

     Get-ChildItem$divSearchDirectory -Filter$fileSearch -Recurse -ErrorVariable FileErrors

    Then parse the errors for the names that failed.


    • Proposed as answer by clayman2 Thursday, July 13, 2017 4:44 PM
    Thursday, July 13, 2017 4:43 PM
  • That did the trick, thanks!
    Thursday, July 13, 2017 5:02 PM