自动化时,“无法获得Workbooks类的Open属性”

时间:2018-07-13 18:00:04

标签: excel powershell csv

我有一些PowerShell脚本,这些脚本调用SQL命令,获取结果并将其放入CSV文件中,然后将CSV文件放入excel工作簿中,并通过电子邮件发送到通讯组列表中。我在运行SQL 2008的较旧Windows 2008服务器上通过Windows计划任务运行这些报告没有问题。但是我已迁移到运行SQL 2016的Windows2016。现在当我通过计划任务运行此过程时,出现以下错误:

Unable to get the Open property of the Workbooks class
At C:\PowerShell\scrpits\ArtiReport3.ps1:607 char:1
+ $workbook = $excel.Workbooks.Open($csvFilePath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

如果我手动运行PowerShell脚本,则不会出现任何问题,并且一切运行正常。我使用相同的登录名来手动运行脚本,就像通过预定任务一样。这是脚本。

$query = "*SQL Query runs here*"

#Edit these peramters for the server this will be running on#
$smtpServer = "*server*";
$smtpFrom = "I3Reports@server.com";
$smtpTo = "*email list here*”
$messageSubject = "I3 Report";

#create anonymus loging for sending e-mail#
$User = "anonymous";
$PWord = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
$Creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $pword


$date = (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')
$date = $date+"_I3Report.xls";

$csvFilePath = "c:\Scripts\queryresults.csv"
$excelFilePath = "c:\scripts\$date"


$instanceName = "*server*"
Import-Module "sqlps"
$results = Invoke-Sqlcmd -QueryTimeout 7200 -Query $query -ServerInstance $instanceName

# Output to CSV
$results | export-csv  $csvFilePath -Delimiter "    " -NoTypeInformation
#this line will remove all the quotation marks from the csv file
(Get-Content $csvFilePath) | % {$_ -replace '"', ""} | out-file -FilePath $csvFilePath -Force 

# Convert CSV file to Excel


$excel = New-Object -ComObject excel.application 
$excel.visible = $False 
$excel.displayalerts=$False 
$workbook = $excel.Workbooks.Open($csvFilePath) #<-- Program fails here
$workSheet = $workbook.worksheets.Item(1) 
#$workSheet.cells.item(3,3) = "HOPLA"

#for freezing pane#
$workSheet.application.activewindow.splitcolumn = 0
$workSheet.application.activewindow.splitrow = 1
$workSheet.Range("A2").application.activewindow.freezepanes = $true
$resize = $workSheet.UsedRange 
$resize.EntireColumn.AutoFit() | Out-Null 
$xlExcel8 = 43
$workbook.SaveAs($excelFilePath, $xlExcel8)
$workbook.Close()
$excel.quit() 
$excel = $null

send-mailmessage -from $smtpFrom -to $smtpTo -subject "$messageSubject" -body "Attachment" -Attachments $excelFilePath -smtpServer $smtpServer -Credential $creds;

如上所述,当我在PowerShell中手动运行它时,此方法有效,但是通过计划的任务,它会收到该错误,并且引用了我在代码中指出的部分。我已经为此工作了好几天,但似乎无法弄清楚是什么原因引起的。欢迎任何帮助或建议。感谢您抽出宝贵的时间。

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决此问题的方法

Powershell Excel Automation - Save/Open fails in Scheduled Task

创建文件夹并获得对它们所在目录的访问权对我来说是成功的。