Powershell Excel Automation - Save/Open fails in Scheduled Task

北战南征 提交于 2019-12-01 09:38:13

问题


I created a simple powershell script that will create an excel instance and save a workbook:

$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Open("C:\Test\foo.xls")
$workbook.SaveAs("C:\Test\bar.xls")

# cleanup code ...

When I run this from powershell directly it works fine. I created a scheduled task that runs it, and when I have the option set that will "Run only when the user is logged in" then it will run fine.

When I change this option to run whether the user is logged in or not, it will fail trying to open/save the file. The account I am using has the correct permissions. I have the account set up to Log in as a service.

Any suggestions?


回答1:


I remember having to do something similar in a C# application, which went well when you build it on Visual Studio, but running under a service on the CI server failed. This I believe is the limitation of Office Automation itself and Microsoft doesn't recommend / support doing this at all Look at Considerations for server-side Automation of Office here - http://support.microsoft.com/kb/257757. It shows the problems and the alternatives.

In my case, I had to give up Office Interop, and use EPPlus ( http://epplus.codeplex.com/ ) to work with excel. It worked great and was much faster as well.




回答2:


I've been burned by this and didn't want to rewrite the code. I saw your post and several others which made me about to give up. However, my persistence paid off. I was trying to have Jenkins run a script to inventory our production environment and output to Excel. I didnt want a text doc because I was highlighting software versions that didnt match in RED, so needed Excel.

Here is the answer that worked for me:

You have to create a folder (or two on a 64bit-windows):

(32Bit, always)

C:\Windows\System32\config\systemprofile\Desktop

(64Bit)

C:\Windows\SysWOW64\config\systemprofile\Desktop

Link that someone provided as the source:

http://www.patton-tech.com/2012/05/printing-from-scheduled-task-as.html

My source was:

http://social.technet.microsoft.com/Forums/en/winserverpowershell/thread/aede572b-4c1f-4729-bc9d-899fed5fad02



来源:https://stackoverflow.com/questions/7112967/powershell-excel-automation-save-open-fails-in-scheduled-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!