Excel won't run in PS script from task scheduler

I have a fairly simple two part task that I want to run daily via the task scheduler:

  • Make a backup of a spreadsheet

  • Open the backup copy in Excel and save it as a CSV file
  • The script below runs fine interactively, however, Excel never launches when run from the task scheduler. It’s as if PowerShell cannot fine the Excel COM object. Excel was installed on this server specifically for this task. It is PS v4 on Windows Server 2008 R2.

    $dir = "D:\foo2_sys\ExportCodes"
    # Make backup copy of spreadsheet
    $lwt = (Copy-Item -Path (Join-Path $dir "EXPORT CODES 2012.xls") `
        -Destination (Join-Path $dir "ExportCodesBackup.xls") `
        -Force -PassThru -ErrorAction Stop).LastWriteTime
    "Job run on         $(Get-Date)
    Codes last updated $lwt" |
        Out-File -FilePath (Join-Path $dir "timestamp.txt") -Encoding ascii
    Remove-Item -Path $dir\ExportCodes.csv -ErrorAction SilentlyContinue
    # Convert to CSV for import into shipping programs.
    $xl = new-object -comobject excel.application
    $xl.Visible =$false
    $Workbook = $xl.workbooks.open((Join-Path $dir "ExportCodesBackup.xls”),0,$True)
    $Workbook.Saved = $True
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) | Out-Null

    Scheduled Tasks often have difficulty launching GUI apps that expect desktop interaction. This isn’t really a PowerShell thing, unfortunately, it’s an interaction between Excel and the Task Scheduler and the way they both behave.

    One of the many, many reasons I hate storing data in Excel.


    See this thread (my suggestion regarding different topic, however my suggestion applies here I think):




    Try creating this folder: “C:\Windows\System32\config\systemprofile\Desktop” (and “C:\Windows\SysWOW64\config\systemprofile\Desktop”, if you’re on a 64-bit OS and are launching a 32-bit version of Excel.) Sometimes this allows Excel to function from a service or scheduled task, though I couldn’t really tell you why. See Excel 2007 automation on top of a Windows Server 2008 x64 for the thread where I originally discovered this trick.

    Note that Microsoft doesn’t support using Office in this fashion.