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
$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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With