Search code examples
powershellwindows-7windows-server-2012

How can I tell if a specific ProcessName is running without crashing


Lets say there is an application with the name exampleService that should be running on Server1. This code works if it is running. However when it's not running, it crashes.

$application = Get-Process -ComputerName Server1 -Name "exampleService"

I get this crash if the application is not running. Is there a more graceful way of finding out if it's not running (without crashing)

Get-Process : Cannot find a process with the name "exampleService". Verify the process name and call the cmdlet again.
At line:1 char:16
+ $application = Get-Process -ComputerName Server1 -Name "exampleService"
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Sampler:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

Also is it possible to launch the application on the Server if it's not running?

The Server is running Windows Server 2012. The PowerShell commands are being run from a Windows 7 64-bit PC.


Solution

  • Look at using -ErrorAction SilentlyContinue to keep that error from displaying. You can use that in an If statement to launch the application if it isn't running.

    --Updated to include launching the remote process

    If (-NOT (Get-Process -Computername Server1 -name "cmd" -ErrorAction SilentlyContinue)) { 
        Write-Host "Launch application"
        $application = "c:\windows\system32\cmd.exe" 
        $start = ([wmiclass]"\\Server1\Root\CIMV2:win32_process").Create($application)
    }