Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. ### Finds all xls files in a given folder and then checks to see if an xlsx copy of the file already exists before converting.
  2. ### Optional flags below can be set to remove the xls file while gathering the list of files and/or after converting.
  3.  
  4. # Search Folder and SubFolders
  5. $Recurse = $true
  6.  
  7. # If xls and xlsx verions of the same file exists - remove xls file
  8. $RemoveOriginalOnCheck = $true
  9.  
  10. # Remove orignal xls file when xlsx is created
  11. $RemoveOriginal = $true
  12.  
  13. ## Path to excel documents
  14. [System.IO.DirectoryInfo] $FolderPath = "C:\Users\landonl\Desktop\New folder"
  15.  
  16. Add-Type -AssemblyName Microsoft.Office.Interop.Excel
  17. $xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
  18.  
  19. Write-Progress -Activity "Converting XLS to XLSX" -Status "Gathering Files from $FolderPath" -PercentComplete 0
  20. if($Recurse){$Files = Get-ChildItem -Path $FolderPath -Recurse}else{$Files = Get-ChildItem -Path $FolderPath}
  21. $Files = $Files | where {$_.Extension -eq ".xls"}
  22.  
  23. $FileCount = 0
  24. $FilesToConvert = $Files | Foreach {
  25. $FileCount++
  26. Write-Progress -Activity "Converting XLS to XLSX" -Status "Checking to see if a xlsx copy exisists in the same folder for $_.Name" -PercentComplete (($FileCount / $Files.Count) * 100)
  27. [System.IO.FileInfo] $SaveAs = $_.FullName.Split(".")[0] + ".xlsx"
  28. if($SaveAs.Exists -eq $false){$_}else{
  29. Write-Host "$SaveAs already exists"
  30. if($RemoveOriginalOnCheck){Remove-Item $_.FullName}
  31. }
  32. }
  33.  
  34. #Open Excel
  35. $excel = New-Object -ComObject excel.application
  36. $excel.visible = $false
  37.  
  38. #Start Converting Files
  39. $FileCount = 0
  40. $FilesToConvert| Foreach {
  41. $FileCount++
  42. Write-Progress -Activity "Converting XLS to XLSX" -Status "Saveing $_.Name as XLSX" -PercentComplete (($FileCount / $Files.Count) * 100)
  43.  
  44. $SaveAs = $_.FullName.Split(".")[0] + ".xlsx"
  45.  
  46. $workbook = $excel.workbooks.open($_.FullName)
  47. $workbook.saveas($SaveAs, $xlFixedFormat)
  48. $workbook.close()
  49.  
  50. if($RemoveOriginal){Remove-Item $_.FullName}
  51.  
  52. }
  53.  
  54. #Close Excel
  55. $excel.Quit()
  56. $excel = $null
  57.  
  58. [gc]::collect()
  59. [gc]::WaitForPendingFinalizers()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement