Powershell - 将 .XLS 文件转换为 .XLSX

Powershell - Convert .XLS file to .XLSX

我目前正在开发一个 powershell 脚本,可以将 excel 文件从 .xls 转换为 .xlsx

准确地说,我需要它以某些方式工作:

  1. 我需要从一个文件夹抓取 .xls 文件并复制到备份文件夹

  2. 将它们转换为 .xlsx 并将它们上传到上传文件夹

将它们从一个文件夹转换并上传到另一个文件夹工作正常,但我尝试添加一些功能,但现在我卡住了。

这是我尝试 运行:

时的错误
At C:\Users\Test\Conv_XLS_V2.ps1:40 char:2
+ }
+  ~ The Try statement is missing its Catch or Finally block. At C:\Users\Test\Conv_XLS_V2.ps1:20 char:16
+ ForEach-Object { ~

      
Missing closing '}' in statement block or type definition.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : MissingCatchOrFinally

我的代码:

# set folders
$downloadfolder = "C:\Users\Test"
#$downloadfolder = "folder that gets the .xls files"
$uploadfolder = "C:\Users\Test\Upload"
#$uploadfolder = "folder that uploads the .xlsx files"
$backupfolder = "C:\Users\Test\Backup"
#$backupfolder = "folder that has .xls files as backup"

#open and convert xls to xlsx
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
write-host $xlFixedFormat
$excel = New-Object -ComObject excel.application
$excel.visible = $true
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype -recurse | 
ForEach-Object {
    try {
        $xlsfilename = $_.fullname
        #copy file to backup folder
        Copy-Item  -Path $xlsfilename -Destination $backupfolder
        # open the xls
        Write-Output "Converting $xlsfilename"
        $workbook = $excel.workbooks.open($xlsfilename)
        # save converted file (as xlsx)
        $xlsxfilename = $xlsfilename + "x"
        $workbook.saveas($xlsxfilename, $xlFixedFormat)
        $workbook.close()
        #remove old file
        Write-Output "delete & move file(s)"
        Remove-Item -Path $xlsfilename -Force
        Move-Item -Path $xlsxfilename -Destination $uploadfolder -Force

    # garbage collection
    [gc]::collect()
    [gc]::WaitForPendingFinalizers()
}
# close excel
$excel.Quit()
$excel = $null

有人可以看看吗?

该错误描述了一个语法问题。您包含了一个 try { 语句,但没有用 } catch {} 块将其关闭。就这些了。

错误信息很清楚。您忘记用结束括号 } 关闭 try{..} 块,并且 try{..} 后面应该跟一个或多个 catch{..} 块以及可选的 finally{..}块。
您可以在 about Try Catch Finally.

上阅读相关内容

然后,还有其他一些错误 and/or 也可以在您的代码中进行改进。

  • $folderpath 未定义,应该是源文件夹 $downloadfolder
  • 使用 -Filter 而不是 -Include 因为它要快得多。你也遗漏了 '*.xls'
  • 中的点
  • 将开关 -File 附加到 Get-ChildItem cmdlet 以确保您不会接收并尝试处理目录
  • 可以将转换后的.xlsx文件直接保存到上传文件夹,无需先创建再移动
  • 要删除使用过的 COM 对象,请先从内存中释放它们,然后启动垃圾收集。
    退出 Excel 后执行此操作 Excel。
# set folders
$downloadfolder = "C:\Users\Test"         # folder where the .xls files are
$uploadfolder   = "C:\Users\Test\Upload"  # folder that uploads the .xlsx files
$backupfolder   = "C:\Users\Test\Backup"  # folder that has .xls files as backup

# open and convert xls to xlsx
Add-Type -AssemblyName Microsoft.Office.Interop.Excel
$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false  # it is much faster if Excel is not visible

# loop through the .xls files and process them
Get-ChildItem -Path $downloadfolder -Filter '*.xls' -Recurse -File | 
ForEach-Object {
    try {
        $xlsfilename = $_.FullName
        #copy file to backup folder
        Copy-Item -Path $xlsfilename -Destination $backupfolder -Force
        # open the xls
        Write-Host "Converting $xlsfilename"
        $workbook = $excel.Workbooks.Open($xlsfilename)
        # save converted file (as xlsx) directly to the upload folder
        $newfilename = Join-Path -Path $uploadfolder -ChildPath ('{0}.xlsx' -f $_.BaseName)
        $workbook.SaveAs($newfilename, $xlFixedFormat)
        $workbook.Close()
        #remove old file
        Write-Host "Delete old file '$xlsfilename'"
        Remove-Item -Path $xlsfilename -Force
    }
    catch {
        # write out a warning as to why something went wrong
        Write-Warning "Could not convert '$xlsfilename':`r`n$($_.Exception.Message)"
    }
}
# close excel
$excel.Quit()
# garbage collection
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()