Try,Catch in a Variable

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Rob Campbell Rob Campbell 2 years, 6 months ago.

  • Author
    Posts
  • #15636
    Profile photo of techguytj
    techguytj
    Member

    I came accross a script the other day that did something like this

    $Vals = try {
    invoke-command -Computername $computer -erroraction stop -scriptblock { $x = get-process; return $x}
    } catch {
    "$computer – HAS A PROBLEM"
    }

    I'm interested if anyone else is using this technique why or why not. And is it a good and efficient way to use the Try-Catch block?

  • #15641
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I haven't done that with try/catch, personally, though I have used similar assignments of the result from foreach, if, and switch. Sometimes I forget that this is even possible in PowerShell, since the syntax looks so similar to C#.

    I'm kind of ambivalent about how try/catch was used here. They're not really suppressing the error, but they are throwing away the details. "Computer HAS A PROBLEM" is something you'd see in a bad help desk ticket: thanks a lot, man, would you like to perhaps describe the problem? 🙂

  • #15645
    Profile photo of techguytj
    techguytj
    Member

    totally get the "Help" message. This was more of a "didn't know you could do that" with the Try/Catch block and wanted to know what is the proper way of doing something like this instead of building an object with the information.

  • #15646
    Profile photo of Rob Campbell
    Rob Campbell
    Participant

    I don't think whether you build an object in the script block is going to have any effect one way or the other, as far a sthe Try/Catch goes. It's being applied to the Invoke-Command that's run on the local system. About the only effect it's going to have is to make the remote system collect all the process data before it can return anything.

You must be logged in to reply to this topic.