Korzax

powershell - fix lookups in excel files

Mar 23rd, 2023
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.02 KB | None | 0 0
  1. ############################
  2. #Improved version of a previous PS script. This turns off calculations and uses link manager to look at links
  3. #FInds broken Vlookup links in excels files
  4. #Makes backup of files before editing
  5. #Prompts user for correct directory - Note needs full directory path of file, ex c:\temp\tester.xlsx
  6. #Goes through and updates all cells that are referencing the same document
  7. #Will prompt again if detects a different source
  8. #
  9. #
  10. #
  11. #THE SCRIPT IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12. #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  13. #WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SCRIPT OR THE USE OR OTHER DEALINGS IN THE SCRIPT.
  14. #USE AT YOUR OWN RISK
  15. ############################
  16.  
  17.  
  18.  
  19.  
  20. # This function creates a log file at the current location if it doesn't already exist
  21. # and returns the path to the log file
  22. function Create-LogFile {
  23. $LogFilePath = (Get-Location).Path + "\BrokenLinksLog.txt"
  24. if (!(Test-Path $LogFilePath)) {
  25. New-Item -Path $LogFilePath -ItemType "File" -Force
  26. }
  27. return $LogFilePath
  28. }
  29.  
  30. # This function writes a message to the specified log file with a timestamp
  31. function Write-Log {
  32. param (
  33. [string]$Message,
  34. [string]$LogFilePath
  35. )
  36. $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
  37. $Message = $Timestamp + " " + $Message
  38. Add-Content -Path $LogFilePath -Value $Message
  39. }
  40.  
  41. # Create a new instance of Excel and hide it from the user
  42. $Excel = New-Object -ComObject Excel.Application -Property @{Visible = $false; DisplayAlerts = $false}
  43.  
  44. # Prompt the user to enter the path of the directory where the Excel files are located
  45. $DirectoryPath = Read-Host "Please enter the path of the directory where the excel files are located"
  46.  
  47. # Prompt the user to choose whether to create a backup of the original files before making changes
  48. $CreateBackup = Read-Host "Do you want to create a backup of the original files before making changes? (y/n)"
  49.  
  50. # Create a log file
  51. $LogFilePath = Create-LogFile
  52.  
  53. # Get a list of all Excel files in the specified directory and its subdirectories
  54. $Files = Get-ChildItem -Path $DirectoryPath -Include *.xls, *.xlsx -Recurse
  55.  
  56.  
  57. # Loop through each file and check for broken links
  58. foreach ($File in $Files) {
  59. Write-Host "Processing file: $($File.FullName)"
  60. Write-Log -Message "Processing file: $($File.FullName)" -LogFilePath $LogFilePath
  61. $WorkBook = $Excel.Workbooks.Open($File.FullName)
  62.  
  63. # Set calculation to manual to improve performance
  64. $Excel.Calculation = -4135 # xlCalculationManual
  65.  
  66.  
  67. # If the user chose to create a backup, save a copy of the original file
  68. if ($CreateBackup -eq "y" -or $CreateBackup -eq "Y") {
  69. $BackupName = $File.DirectoryName + "\Backup_" + $File.Name
  70. $WorkBook.SaveCopyAs($BackupName)
  71. }
  72.  
  73. try {
  74. # Set calculation to manual to improve performance
  75. $Excel.Calculation = -4135 # xlCalculationManual
  76.  
  77. # Replace the previous loop through each worksheet with the new code
  78. $LinkSources = $WorkBook.LinkSources(1) # xlExcelLinks
  79. if ($LinkSources -ne $null) {
  80. foreach ($OldFilePath in $LinkSources) {
  81. # Check if the file path stored in $OldFilePath is valid
  82. if (!(Test-Path $OldFilePath)) {
  83. # If it is a new broken link, write a message to the console and the log file
  84. Write-Host "Path not found: $($OldFilePath)"
  85. Write-Log -Message "Path not found: $($OldFilePath)" -LogFilePath $LogFilePath
  86.  
  87. # Prompt the user to enter the correct path for the broken link
  88. $NewPath = Read-Host "The link $($OldFilePath) in the file $($File.FullName) is broken. Please enter the correct path:"
  89.  
  90. # Update the broken link with the new path entered by the user
  91. $WorkBook.ChangeLink($OldFilePath, $NewPath, 1) # xlLinkTypeExcelLinks
  92. }
  93. }
  94. }
  95. } catch {
  96. # Catch any exceptions that occur during the processing of the current cell and write them to the console and the log file
  97. Write-Host "Error processing $($File.FullName): $($_.Exception.Message)"
  98. Write-Log -Message "Error processing $($File.FullName): $($_.Exception.Message)" -LogFilePath $LogFilePath
  99. } finally {
  100. # Set calculation back to automatic after processing
  101. $Excel.Calculation = -4105 # xlCalculationAutomatic
  102. $WorkBook.Save()
  103. $WorkBook.Close()
  104. }
  105. }
  106.  
  107. $Excel.Quit()
  108. [System.Runtime.InteropServices.Marshal]::ReleaseComObject($Excel) | Out-Null
  109. [System.GC]::Collect()
  110. [System.GC]::WaitForPendingFinalizers()
  111.  
  112. Write-Host "Script execution completed."
  113. Write-Log -Message "Script execution completed." -LogFilePath $LogFilePath
Advertisement
Add Comment
Please, Sign In to add comment