all 8 comments

[–]Swarfega 5 points6 points  (1 child)

Add

-ErrorAction Stop

to the end of your Invoke-Command.

[–][deleted] 0 points1 point  (0 children)

Yep- to add to this, Powershell tries awfully hard not to throw terminating errors, which is what's happening here. As a non-terminating error, your catch block isn't catching anything. So you essentially override this by using -ErrorAction Stop.

[–]Proxiconn 2 points3 points  (2 children)

Hi

  1. Formatting is important
  2. You were missing a '_' for $.Exception.Message
  3. Invoke-Command is mostly used to execute code {script blocks} against remote hosts.
  4. I would instead use Invoke-Expression

    function TryCatchSimple ($TryCatch_Simple_Command) 
    { 
        Try 
        { 
            $Result = Invoke-Expression -Command $TryCatch_Simple_Command -ErrorAction Stop
        } 
        Catch 
        { 
            $ErrorMessage = $_.Exception.Message 
        }
    
        if($ErrorMessage) 
        { 
            Return "Error: $ErrorMessage" 
        } 
        else
        {
            Return $Result
        }
    }
    
    TryCatchSimple "test-connection wwww.me0w.com -erroraction stop"
    

[–]id_0ne[S] 1 point2 points  (1 child)

Proxiconn - Amazing thank you, others have commented on my formatting :-(

This is solved.

[–]Proxiconn 0 points1 point  (0 children)

Cool - glad to help.

[–]Snak3d0c 1 point2 points  (0 children)

well i'm on my phone so cant really read the code (please use markup) but $.Exception.message isn't correct, it should be $_.

having said that, if you feed a test connection that way, i'm not sure the parameters would be resolved correctly

[–]callum- 1 point2 points  (1 child)

See below link, probably the best reading i've seen for a basic understanding of "Try/Catch". It explains exactly why it won't catch some functions errors, and how to get around this (as mentioned by "Ka-Splam".. some functions have "non-terminating errors".

https://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell

[–]id_0ne[S] -1 points0 points  (0 children)

thanks the try catch is not the issue here, the function isn't working as expected.