Wednesday, August 5, 2015

Use Powershell: Start Application If Not Running

Script Contents:

$processname = "notepad" 
$processlocation = "c:\windows\system32\notepad.exe" 

$ErrorActionPreference = "SilentlyContinue" 

if (get-process $processname){ 
    write-host "Application running..." -fo Green 
} ELSE { 
    write-host "Application not found... Starting..." -fo Red 
    & $processlocation 
    if (get-process $processname){ 
        write-host "Application Running..." -fo Green 
    } ELSE { 
        write-host "Application failed to start..." -fo Red 
    } 
}

Explanation:

This is a simple script the demonstrates how easily Powershell can be used to perform intelligent tasks. We start out with two variables. The first is the process name ($processname). A quick exercise demonstrating how to gather this information can be performed by opening a shell and running "tasklist" while the process is running. See the example below -

Next we enter in the launch parameters to start the process ($processlocation). If your not sure what this is, you'll have to do a little research. This is what you would type in the run dialog or cmd prompt to start the application/process.

From there we drop into an "if" statement. We use "get-process" to determine if the process is running or not.
If the process is running, we get a nice little output (if not running as a scheduled task or silently) that states the process is already running. If the process isn't running, we invoke the run command specified earlier in $processlocation. From there we drop into a verification similar similar to the parent if statement.
if (get-process $processname){ 
    write-host "Application Running..." -fo Green 
} ELSE { 
    write-host "Application failed to start..." -fo Red 
}
If successfully started, we should get a nice green output stating the application is running. If not, the output will say the contrary.

Tip: When testing, it is best to work on the script in Powershell ISE. This will let you to modify the script and run it on the fly, without having to go back and forth between the shell and your text editor. This will also help with troubleshooting as you will be able to see the errors. To enable error messages, comment out line 5, "$ErrorActionPreference = "SilentlyContinue".

As always, feel free to comment below with requests, suggestions, and questions! Happy scripting.

No comments:

Post a Comment