作为计划任务运行时,Powershell脚本无法访问文件

Bag*_*era 12 com excel powershell scheduled-tasks powershell-2.0

我的Powershell(2.0)脚本包含以下代码段:

$fileName = "c:\reports\1.xlsx"
$xl = new-object -comobject excel.application
$xlFormat = [Microsoft.Office.Interop.excel.XlFileFormat]::xlWorkbookDefault
$xl.displayalerts = $false
$workbook = $xl.workbooks.open($fileName)
#Code to manipulate a worksheet
$workbook.SaveAs($fileName, $xlformat)
$xl.quit()
$error | out-file c:\reports\error.txt
Run Code Online (Sandbox Code Playgroud)

我可以在Powershell命令提示符下运行此脚本,没有任何问题.电子表格会更新,error.txt为空.但是,当我在任务计划程序中将其作为任务运行时,我会在第一行出错.

使用"1"参数调用"打开"的异常:"Microsoft Office Excel无法访问文件'C:\ reports\1.xlsx'.有几个可能的原因:文件名或路径不存在.文件正在尝试保存的工作簿与当前打开的工作簿具有相同的名称.

我使用与Powershell命令提示符中运行脚本相同的凭据运行任务.当我手动运行脚本时,它可以打开,更新和保存电子表格而不会出现任何问题.当我在任务计划程序中运行它时,它无法访问电子表格.

有问题的文件对所有用户都是可读/可写的.我已经验证我可以使用相同的凭据在Excel中打开该文件.如果我创建一个新的电子表格并将其名称作为$ filename,我会得到相同的结果.我已经确认任务管理器中没有Excel.exe实例.

奇怪的是,如果我使用get-content,我没有任何问题.另外,如果我制作新的电子表格,我没有任何问题.

$fileName = "c:\reports\1.xlsx"
$xl = get-content $spreadsheet
$xl = new-object -comobject excel.application
$xlFormat = [Microsoft.Office.Interop.excel.XlFileFormat]::xlWorkbookDefault
$xl.displayalerts = $false
# Commented out $workbook = $xl.workbooks.open($fileName)
$workbook = $xl.workbooks.add()
#Code to manipulate a worksheet
$workbook.SaveAs($fileName, $xlformat)
$xl.quit()
$error | out-file c:\reports\error.txt
Run Code Online (Sandbox Code Playgroud)

这很好.因此Get-ChildItem可以毫无问题地打开文件.如果我手动运行它,ComObject可以打开该文件,但如果它作为任务运行则不能.

我不知所措.有任何想法吗?

Tes*_*ler 20

我想你已经在Excel中遇到了一个错误:

你必须创建一个文件夹(或64位窗口上的两个):

(32位,总是)

C:\ WINDOWS\system32 \设置\ systemprofile \桌面

(64位)

C:\ WINDOWS\Syswow64资料\ CONFIG\systemprofile \桌面

我遇到了同样的问题,这是我找到的唯一解决方案.

来自TechNet论坛(通过自动执行时的PowerShell和Excel问题)