【发布时间】:2014-05-05 09:46:02
【问题描述】:
我的 Powershell (2.0) 脚本有以下代码 sn-p:
$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
我可以毫无问题地在 Powershell 命令提示符下运行此脚本。电子表格得到更新,error.txt 为空。但是,当我在任务计划程序中将其作为任务运行时,第一行出现错误。
使用“1”参数调用“Open”时出现异常:“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
效果很好。所以 Get-ChildItem 可以毫无问题地打开文件。如果我手动运行 ComObject 可以打开文件,但如果它作为任务运行则不能。
我很茫然。有什么想法吗?
【问题讨论】:
-
通过
aws ssm send-command运行时也会出现这个问题 -
您解决了这个问题吗?对我来说,每次都会弹出excel登录窗口。
标签: excel powershell com scheduled-tasks powershell-2.0