Powershell - if a process is not running, start it

前端 未结 4 1757
情深已故
情深已故 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:24

    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.

提交回复
热议问题