58

I am trying to see if a process is running on multiple servers and then format it into a table.

get-process -ComputerName server1,server2,server3 -name explorer | Select-Object processname,machinename

Thats the easy part - When the process does not exist or if the server is unavailable, powershell outputs a big ugly error, messes up the the table and doesn't continue. Example

Get-Process : Couldn't connect to remote machine.At line:1 char:12 + get-process <<<<  -ComputerName server1,server2,server3 -name explorer | format-table processname,machinename
+ CategoryInfo          : NotSpecified: (:) [Get-Process], InvalidOperatio   nException    + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.Power   Shell.Commands.GetProcessCommand

How do I get around this? If the I would still like to get notified if the process isn't available or Running.

Roman
  • 3,825
  • 3
  • 20
  • 33
Jake
  • 2,238
  • 5
  • 30
  • 39

2 Answers2

70

Add -ErrorAction SilentlyContinue to your command.

When it's not an error, but an unhandled Exception, you should add -EV Err -EA SilentlyContinue, in order to catch the exception. (EA is an alias for ErrorAction)

You can then evaluate the error in your script, by having a look at $Err[0]

evandrix
  • 113
  • 1
  • 4
Bart De Vos
  • 17,761
  • 6
  • 62
  • 81
  • I'm afraid that doesnt work unless I'm sticking it in the wrong place. get-process -ComputerName server1, server2, server3 -name explorer -ErrorAction SilentlyContinue | Select-Object processname,machinename – Jake Nov 30 '11 at 11:53
  • Add it to `get-process` or take a look at my updated answer above. – Bart De Vos Nov 30 '11 at 12:04
23

Short answer: Add $ErrorActionPreference = 'SilentlyContinue' at the start of your code so you don't need to add -ErrorAction SilentlyContinue to every command

Long answer: Controlling Error Reporting Behavior and Intercepting Errors

Moby Disk
  • 186
  • 1
  • 10
Tinman
  • 329
  • 3
  • 8
  • 1
    Note the difference: 'Continue' (default setting) continues execution, but writes errors to the console (which op seems to want to get rid of, if I read him correctly). 'SilentlyContinue' suppresses all error-messages entirely. – Frederik Struck-Schøning Aug 10 '16 at 11:44
  • 3
    [**Don’t do that** #17: Silent the errors with `$ErrorActionPreference = ‘SilentlyContinue’`](http://powershell-guru.com/dont-do-that-17-silent-errors-with-erroractionpreference-silentlycontinue/) – JosefZ Jan 27 '18 at 16:33
  • "Add $ErrorActionPreference = 'SilentlyContinue' at the start of your code" ---> This really helped so thank you so much for your Help and making it available on Internet. – Nishant Jul 02 '19 at 12:26
  • 2
    The gitbook link is dead. I think this is a new link to the relevant content: https://devops-collective-inc.gitbook.io/the-big-book-of-powershell-error-handling/controlling-error-reporting-behavior-and-intercepting-errors – Martin Owen Nov 12 '20 at 11:38