Powershell - if a process is not running, start it

前端 未结 4 1765
情深已故
情深已故 2021-02-03 23:37

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

4条回答
  •  广开言路
    2021-02-04 00:28

    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}
    

提交回复
热议问题