0

I currently have a Powershell script that can access Microsoft Outlook, and which I want to be executed automatically every x minutes. For the latter part I created a task in Task Manager that fires the following command:

Powershell.exe -windowstyle minimized -c "powershell -c [PATH_TO_SCRIPT] -verbose >> [PATH_TO_LOG]"

This works perfectly fine, except for the problem that, even with the -windowstyle minimized flag, it still briefly opens a powershell window, that disappears to the background after 2 seconds or so. A solution to this problem is to change the setting in Task Scheduler, checking "Run whether user is logged in or not". However, at that point, my script doesn't execute anymore. From the logs I found that the script runs perfectly fine until the following line:

$outlook = New-Object -ComObject Outlook.Application,

the line on which I open the Outlook application. I'm not sure what the "run whether user is logged in or not" option actually does, but whatever it is, it can no longer access an instance of my Outlook application.

Given what I actually want to achieve, could I tweak either my script or my task to fix this, or is there maybe another way to tackle this?

konewka
  • 620
  • 8
  • 21
  • Has your account been granted the Logon as batch permission? – Bacon Bits Oct 25 '17 at 15:31
  • I'll check! For now it seems I am not an administrator, I'll see if fiddling with these settings solves it – konewka Oct 25 '17 at 15:39
  • Did leave `Do not store password. The task will only have access to local resources` unchecked and supply a password? I presume that a ComObject as Outlook requires more than just local resources. For the *"it still briefly opens a powershell window"* issue, see: https://stackoverflow.com/questions/1802127/how-to-run-a-powershell-script-without-displaying-a-window – iRon Oct 25 '17 at 16:17

1 Answers1

0

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.

As a workaround you may consider using a low-level API instead - Extended MAPI. Or just any other third-party wrapper around that API such as Redemption.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45