Advertisement
shadowsong

Rename-ExcelTabs-v1

Sep 15th, 2020 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # to run, type this in powershell: &"C:\Users\jostae\Documents\SQL Server Management Studio\FixBOMsplitName.ps1"
  2.  
  3. # get a list of xlsx files
  4. $allFiles = Get-ChildItem -Path "C:\Users\jostae\Documents\CM release\" -Filter '*.xlsx' -File
  5.  
  6. # create an Excel object
  7. $xldoc = New-Object -ComObject Excel.Application
  8. $xldoc.Visible = $false
  9. $xldoc.DisplayAlerts = $false
  10.  
  11.  
  12. foreach ($ExcelFile in $AllFiles) {
  13.     # open the file
  14.     $WorkBook = $xldoc.Workbooks.Open($ExcelFile.FullName)
  15.     # count of non AML sheets
  16.     $NotAMLCount = ($WorkBook.Worksheets | where {
  17.         ($_.Name -ne "AML" -and $_.Visible -eq -1)
  18.     }).count
  19.     # non AML sheets that need fixing
  20.     $SplitSheets = $WorkBook.Worksheets | where {
  21.         ($_.Name -ne "AML" -and $_.Name -ne "SPLITS" -and $_.Visible -eq -1)
  22.     }
  23.  
  24.  
  25.     # if no sheets are named incorrectly, no action required
  26.     if(($SplitSheets | measure-object).count -eq 0) {
  27.         $WorkBook.Close()  
  28.         Write-Verbose -Message "$ExcelFile is correct" -Verbose        
  29.     }
  30.     # if there are too many sheets, move to subfolder
  31.     elseif($NotAMLCount -gt 1) {
  32.         $WorkBook.Close()
  33.         Move-Item -Path $ExcelFile.FullName -Destination "C:\Users\jostae\Documents\CM release\tabcheck\"
  34.         Write-Verbose -Message "$ExcelFile has too many sheets" -Verbose   
  35.     }
  36.    
  37.     # otherwise rename non-AML tabs to SPLITS
  38.     elseif($SplitSheets) {
  39.         $SplitSheets.Name = "SPLITS"
  40.         $WorkBook.Save()
  41.         $WorkBook.Close()  
  42.         Write-Verbose -Message "$ExcelFile updated" -Verbose
  43.     }
  44. }
  45.  
  46.  
  47. # clean up
  48. $xldoc.Quit()
  49. $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
  50. $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xldoc)
  51. [System.GC]::Collect()
  52. [System.GC]::WaitForPendingFinalizers()
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement