0

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)
Evan
  • 334
  • 1
  • 6
  • 18

2 Answers2

1

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.

codewario
  • 19,553
  • 20
  • 90
  • 159
  • Oddly enough, using "Start-Sleep -s 1" is enough of a break for the CPU usage to stay down at 7-10% while the script is running. Of course I don't need it to check every second, but still interesting. Thank you for the help! – Evan Jan 16 '20 at 18:47
  • No problem! If this worked for you, consider marking the answer as "Accepted" to help others who may come across this question. – codewario Jan 16 '20 at 18:50
  • 1
    Yeah, I just had to wait for the cooldown on a new question before I could mark it. Thanks again! – Evan Jan 16 '20 at 18:53
1

Another way of solving this problem is running below batchfile (scheduled)

@echo off

SET outlookpath=C:\Program Files\Microsoft Office 15\root\office15\outlook.exe

for /f "usebackq" %%f in (`tasklist /FI "IMAGENAME eq outlook.exe"`) do set a=%%f
REM echo A:%a%

if not "%a%"=="outlook.exe" start "" "%outlookpath%"

If you schedule this to run every 5 minutes, than within 5 minutes after closing outlook, it will start again. If you think 5 minutes is too long, schedule it more often.

Luuk
  • 12,245
  • 5
  • 22
  • 33
  • Thank you for your answer! While I do use Windows Task Scheduler for some of my PS scripts (called via batch scripts), Task Scheduler is not super reliable, so for that reason I am going to stick to my PowerShell implementation. Now a do-while loop could be added to your script, but I just like PowerShell. Thanks again! – Evan Jan 16 '20 at 19:08
  • Keep in mind you can still run PowerShell scripts from task scheduler, just make sure you set the executable to `powershell.exe` and the arguments to `-File C:\path\to\script -Any -Additional -Arguments -You -Need`. The script path can also be a UNC path if the script is on the network in a trusted location. If it is just a one-liner powershell command, you can use `-c "powershell-code here"` for the arguments. – codewario Jan 16 '20 at 19:45