Powershell - if a process is not running, start it

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

    $path = "C:\utilities\prog.exe"        
    $list = get-process | where-object {$_.Path -eq $path }     
    if ($list -eq $null) { start-process -filepath $path }
    

    Or

    $path = "C:\utilities\prog.exe"
    get-process | where-object {$_.Path -eq $path } | measure-object | where-object { $_.Count -eq 0} | foreach-object {start-process -filepath $path }
    

    This will save you the if statement and one variable declaration. It can be a one line command as well:

    1. Get processes
    2. Pick the ones with the path you are interested in
    3. Use measure object to get the stats about the list you have
    4. Continue the piping only if the count value of stats is 0
    5. Start process

    Don't let the foreach at the end put you off. The measure object will return only one item the where will return one or zero. The foreach is only used to execute if the result is zero. It won't start more then one processes. :)

提交回复
热议问题