Excel macros run through powershell but not when run by windows task scheduler

帅比萌擦擦* 提交于 2020-08-19 10:21:34

问题


I have a script which checks a folder for excel files and then if this "threshold" is greater than 0 then a macro from another excel file is run that interact with these excel folders.

When I run the process manually through powershell ISE it works fine but when I use the windows task scheduler the powershell script runs but the excel macro called doesn't run. Any suggestions why this might be the case? This process used to run on a windows 2008 server fine but was migrated to windows server 2012 and won't run properly

  if ($count -gt $threshold){
    $excel = new-object -comobject excel.application

    $workbook = $excel.workbooks.open("D:\TimesheetService\IS-FS - AutoTimesheetLoader v2.3 - UAT.xlsm")

    $worksheet = $workbook.worksheets.item(1)

    $excel.Run("ImportTime")

    $workbook.close($false)

    $excel.quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
    Remove-Variable excel
}

回答1:


You cannot use the COM Automation Excel library (new-object -comobject excel.application) from a scheduled task, unless that task is run in the window station (session) of the currently logged-on user.

That is, in order to use the COM Excel library from a scheduled task, you must have the Run only when user is logged on option chosen for it, which you may not want, for two reasons:

  • It restricts your task to run only when someone happens to be logged on.

  • The currently logged-on user will see the task's window as it runs - unless you take extra steps to hide it (which can't be done with powershell.exe itself).

Note: There is a workaround that is currently effective, but it is unsupported, which is why it is better to avoid it - see this answer to a related superuser.com question.

Therefore, consider alternatives that do not have this restriction, such as the DocumentFormat.OpenXml Nuget package.

See this Microsoft support article for background information.




回答2:


I was trying to do the same thing. This got it working for me https://www.jonashendrickx.com/2016/04/07/when-run-as-scheduled-task-excel-wont-save-with-powershell/

The last two steps is what I needed. Check to make sure these folders exist

On a 32-bit and 64-bit operating system:

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

On a 64-bit operating system:

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



来源:https://stackoverflow.com/questions/60040561/excel-macros-run-through-powershell-but-not-when-run-by-windows-task-scheduler

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