Monday, April 2, 2018

My Process Stopped Processing

Greetings,
Last week I was tasked to create a Powershell script that detects the status of a process running on a Windows 10 computer.  If the process wasn't running, the script had to start the process.  If the process is in a 'suspended' state, the script had to stop and restart the process.  If the process was running, the script display a message.


Detecting the status of the process is relatively simple to do.  The first thing you want to do is store the process information in a variable.  We will call the variable $process:


$process = get-process myprocess -ErrorAction SilentlyContinue


It is necessary to add the -ErrorAction SilentlyContinue in order to get an empty variable if the process is not running.


Once we have the status of the process, you will have to check if the process is running.  To do that we will using an IF statement:


if ($process)
     {
      
     }
else
     {
        invoke-expression "c:\processes\myprocess.exe"
     }


If there is something in the $process variable, then we will check the status of the running process.  If the variable is empty, then we will start the process using invoke-expression (I will explain this later in the article.


So, if $process is not empty, the next step is to determine if the process is responding.  One of the attributes of $process is .Responding.  Within the brackets under the IF statement, use the following commands:
{
     if ($process.Responding)
     {
       Write-Host "Process is running"
     }
     Else
     {
        Stop-Process -name myprocess -Force
        invoke-expression "c:\processes\myprocess.exe"
     }
}


This code checks the status of $process.Responding.  It will either be True or False.  If the process is responding, then a message is returned.  If the process is not responding, the process is stopped by force, and the process is restarted.


The reason for using invoke-expression is because my process has a user interface that must be visible when it is running.  I couldn't use start-process because the interface would not appear.


The entire script will like as follows:
$process = get-process myprocess -ErrorAction SilentlyContinue
if ($process)
     {
       if ($process.Responding)
        {
          Write-Host "Process is running"
        }
     else
        {
          Stop-Process -name myprocess -Force
          invoke-expression "c:\processes\myprocess.exe"
        }
     }
else
     {
        invoke-expression "c:\processes\myprocess.exe"
     }


I hope you find this script helpful.  Be sure to add a comment if you have any questions, comments, or corrections.

No comments:

Post a Comment