【发布时间】:2021-10-21 04:42:20
【问题描述】:
我正在尝试使用带有 COM 对象的 PowerShell 打开、写入和保存现有的 Excel 文件。我需要使用 COM 对象路由,因为现有 Excel 文件使用 Import/Export-Excel PowerShell 模块不支持的公式。 Excel 2016 已安装在服务器上,并且 PowerShell 脚本正在以 SYSTEM 身份启动。
我的代码是:
$excel = New-Object -ComObject Excel.Application
$excelWorkbook = $excel.Workbooks.Open($ServerBuildTrackingFilePath)
$excelWorksheet = $excel.WorkSheets.item("VirtualServerBuild")
$excelWorksheet.Activate()
$xlDown = -4121
$xlUp = -4162
$nextRow = ($excelWorksheet.cells.Range("A1048576").End($xlUp).row) + 1
$excelWorksheet.Cells.Item($nextRow,1) = 'This'
$excelWorksheet.Cells.Item($nextRow,2) = 'is a'
$excelWorksheet.Cells.Item($nextRow,3) = 'Test'
$excelWorkbook.Save()
$excelWorkbook.Close()
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
返回的错误是:
Microsoft Excel cannot access the file '\\domainfilepath\to\ServerBuildTracking.xlsx'. There
are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
At line:7 char:1
+ $excelWorkbook = $excel.Workbooks.Open($ServerBuildFilePath ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
【问题讨论】:
-
还要注意,AD servername$ 对象对正在使用的文件具有完全控制访问权限
标签: excel powershell scripting system comobject