When ran as a scheduled task, cannot save an Excel workbook when using Excel.Application COM object in PowerShell

Posted by Daniel Richnak on Server Fault See other posts from Server Fault or by Daniel Richnak
Published on 2011-05-05T22:15:43Z Indexed on 2012/11/13 23:05 UTC
Read the original article Hit count: 259

I'm having an issue where I've automated creating an Excel.Application COM object, add some data into a workbook, and then saving the document as an xlsx.

This works fine if:

  • I'm already in Powershell interactive host and either run each command in sequence, or execute as a ps1.
  • I run it from cmd.exe, using the syntax: powershell.exe -command "c:\path\to\powershellscript.ps1"
  • I create a scheduled task in Windows 7 / Server 2008 R2, use the above powershell.exe -command syntax, and use the mode "Run only when the user is logged on".

It fails when I modify the same scheduled task, but set it to "run whether the user is logged on or not".

Here's a sample script that illustrates the problem I'm having:

$Excel = New-Object -Com Excel.Application
$Excelworkbook = $Excel.Workbooks.Add()
$excelworkbook.saveas("C:\temp\test.xlsx")
$excelworkbook.close()

I have a theory that the COM object fails somehow if my profile isn't loaded / if it's not performed in a command window.

Any ideas on which options to choose when creating the scheduled task, or which options to use when creating the Excel object or using the SaveAs() function? Can anybody reproduce this? I've been able to see this behavior on both a Server 2008 R2 machine, and Windows 7. Haven't tried other platforms.

© Server Fault or respective owner

Related posts about windows-server-2008

Related posts about powershell