Search code examples
performancepowershellpowershell-4.0powershell-5.0processing-efficiency

Continuously check if a process is running


I have a little code I wrote that checks to see if Outlook is running, and if it is not, opens Outlook. The problem is that my work PC tends to idle around 7% usage, but spikes up to the upper 30s while the script is running. If it detects that Outlook is no longer active, CPU usage can spike up to nearly 100% while opening Outlook. This ~33% increase while the script is running could cause problems when I am working. Is there another way to accomplish the functionality of my code while using less processing power?

do{
    $running = Get-Process outlook -ErrorAction SilentlyContinue
    if (!$running)
    {
        Start-Process outlook
    }
} while (1 -eq 1)

Solution

  • You need to add a Start-Sleep in there, to keep the script from continuously using CPU time. Otherwise it's continuously looping without rest, making sure Outlook is running. At the end of your do-block:

    Start-Sleep -s 60
    

    You can adjust the number of seconds, or even specify milliseconds instead with the -m parameter you require it.