Try,Catch in a Variable

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?

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? :slight_smile:

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.

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.