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
{}
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
It is possible to create a block of code that should be evaluated further in your code by wrapping it in {} (a scriptblock):
However, if you’re looking for a short one-liner to solve your problem: