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 wit
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}