Powershell脚本第一次出错,但在第二次尝试时有效



我有一个Powershell脚本,可以搜索xls文件并将它们转换为xlsx。每次我第一次运行它时,我都会得到错误

Unable to find type [Microsoft.Office.Interop.Excel.XlFileFormat].
At C:UserswpaulingDocumentsQuarter Report Scriptsconvert.ps1:2 char:18
+ ... xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpen ...
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (Microsoft.Offic...el.XlFileFormat:TypeName) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound

但是,当我第二次运行它时,一切都按预期工作,我发疯了。这是我的脚本

#Converts xls into xlsx
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $false
$folderpath = "C:Usersuser1DocumentsQ4"
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype -recurse | 
ForEach-Object `
{
$path = ($_.fullname).substring(0, ($_.FullName).lastindexOf("."))
"Converting $path"
$workbook = $excel.workbooks.open($_.fullname)
$path += ".xlsx"
$workbook.saveas($path, $xlFixedFormat)
$workbook.close()
remove-item $_.fullname
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()

脚本以以下行开头

Add-Type -AssemblyName Microsoft.Office.Interop.Excel

希望有帮助。

附言当然,描述性要少得多,但您也可以对变量使用数字枚举值51,而不使用Add-Type

请参见: Xl文件格式枚举

相关内容

最新更新