Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - if a process is not running, start it

Tags:

powershell

Noob help please. I'm trying to write a script that will check if a process is running, and if not, start it. If the process is running, it should do nothing. I've come up with the following so far but it is starting a new instance of the process regardless of whether it was running already. Any help is appreciated.

$Prog = "C:\utilities\prog.exe" $Running = Get-Process prog -ErrorAction SilentlyContinue $Start = ([wmiclass]"win32_process").Create($Prog) if($Running -eq $null) {$Start} else {} 
like image 279
Charlotte Avatar asked Jan 12 '12 11:01

Charlotte


2 Answers

First of all, here's is what is wrong in your code. In your code, the process is created before you evaluate whether your program is already running

$Prog = "C:\utilities\prog.exe" $Running = Get-Process prog -ErrorAction SilentlyContinue $Start = ([wmiclass]"win32_process").Create($Prog) # the process is created on this line if($Running -eq $null) # evaluating if the program is running {$Start} 

It is possible to create a block of code that should be evaluated further in your code by wrapping it in {} (a scriptblock):

$Prog = "C:\utilities\prog.exe" $Running = Get-Process prog -ErrorAction SilentlyContinue $Start = {([wmiclass]"win32_process").Create($Prog)}  if($Running -eq $null) # evaluating if the program is running {& $Start} # the process is created on this line 

However, if you're looking for a short one-liner to solve your problem:

if (! (ps | ? {$_.path -eq $prog})) {& $prog} 
like image 127
jon Z Avatar answered Sep 18 '22 22:09

jon Z


In the Get-Process cmdlet, the process name argument must be the name of the executable without the file extension. Try substituting $Prog = "C:\utilities\prog.exe" with $Prog = "prog".

In my opinion, your script would be more readable if you filtered the process out using the Where-Object cmdlet instead. Here's an example:

$programName = "prog" $isRunning = (Get-Process | Where-Object { $_.Name -eq $programName }).Count -gt 0  if ($isRunning)  # ... else  # ... 

That way you can get rid of the -ErrorAction SilentlyContinue argument, which can be confusing to someone who is not aware of the fact that Get-Process throws an error if it can't find a process with the specified name.

like image 24
Enrico Campidoglio Avatar answered Sep 17 '22 22:09

Enrico Campidoglio