Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### Finds all xls files in a given folder and then checks to see if an xlsx copy of the file already exists before converting.
- ### Optional flags below can be set to remove the xls file while gathering the list of files and/or after converting.
- # Search Folder and SubFolders
- $Recurse = $true
- # If xls and xlsx verions of the same file exists - remove xls file
- $RemoveOriginalOnCheck = $true
- # Remove orignal xls file when xlsx is created
- $RemoveOriginal = $true
- ## Path to excel documents
- [System.IO.DirectoryInfo] $FolderPath = "C:\Users\landonl\Desktop\New folder"
- Add-Type -AssemblyName Microsoft.Office.Interop.Excel
- $xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbook
- Write-Progress -Activity "Converting XLS to XLSX" -Status "Gathering Files from $FolderPath" -PercentComplete 0
- if($Recurse){$Files = Get-ChildItem -Path $FolderPath -Recurse}else{$Files = Get-ChildItem -Path $FolderPath}
- $Files = $Files | where {$_.Extension -eq ".xls"}
- $FileCount = 0
- $FilesToConvert = $Files | Foreach {
- $FileCount++
- 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)
- [System.IO.FileInfo] $SaveAs = $_.FullName.Split(".")[0] + ".xlsx"
- if($SaveAs.Exists -eq $false){$_}else{
- Write-Host "$SaveAs already exists"
- if($RemoveOriginalOnCheck){Remove-Item $_.FullName}
- }
- }
- #Open Excel
- $excel = New-Object -ComObject excel.application
- $excel.visible = $false
- #Start Converting Files
- $FileCount = 0
- $FilesToConvert| Foreach {
- $FileCount++
- Write-Progress -Activity "Converting XLS to XLSX" -Status "Saveing $_.Name as XLSX" -PercentComplete (($FileCount / $Files.Count) * 100)
- $SaveAs = $_.FullName.Split(".")[0] + ".xlsx"
- $workbook = $excel.workbooks.open($_.FullName)
- $workbook.saveas($SaveAs, $xlFixedFormat)
- $workbook.close()
- if($RemoveOriginal){Remove-Item $_.FullName}
- }
- #Close Excel
- $excel.Quit()
- $excel = $null
- [gc]::collect()
- [gc]::WaitForPendingFinalizers()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement