Monday, November 12, 2012

Failing Office automation when run from a service

Scenario: I needed to create a small script to automate the conversion of a Word document into PDF. There's plenty of help out there to script this by using the Microsoft.Office.Interop namespace, for example this simple one. I tried both writing a Powershell script and a compiled C# .exe with the same result: When running from the desktop, everything works fine, whileas running from a scheduled task or from CruiseControl running as a system service failed. If CruiseControl was running from its debug console window however, everything ran fine.

Problem: It seemed clear that the Office libraries required a logged on session to run in, as  also Microsoft confirms here in their Q257757 article.

Solution/workaround: I came across this hack - reposting it here for my own easy access to the knowledge:
  1. Browse to or create this folder: C:\Windows\SysWOW64\config\systemprofile\Desktop on 64 bits Win7/Win2008 - for 32-bits Windows, substitute SysWOW64 part of the path with System32. You might have to change some permissions to get there and you of course need to have administrative rights.
  2. Make sure the user credentials running the service or scheduled task you want to use has full control access permissions to the folder.
I have no idea how this trick can make it all work, but it does - at least in my case. Since Microsoft does not recommend or describe it however - use solely at your own risk. Not suitable for rocket launchers, weapon systems etc..

No comments: