Created
August 10, 2018 20:30
-
-
Save Szeraax/ddbaeb316d98c121961a1555500df442 to your computer and use it in GitHub Desktop.
A script to update href links in excel xlsx files when you move files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[cmdletbinding()] | |
Param( | |
[switch]$CopyToNew, | |
$SearchString = "\\OLDSERVER\OLDSHARE\FOLDERNAME", | |
$ReplaceString = "\\NEWSERVER\NEWSHARE\NEWFOLDER", | |
$FolderToSearch = "\\server\share\folder\", | |
$LogResultsLocation = $PSScriptRoot | |
) | |
$Excel = New-Object -ComObject "Excel.Application" | |
$Excel.Visible = $false | |
(ls $FolderToSearch -Recurse -File -Filter *.xlsx) | % { | |
$LinksUpdated = 0 | |
$Workbook = $Excel.Workbooks.Open($_.FullName) | |
$Workbook.Sheets | %{ | |
$_.HyperLinks | ? {$_.Address -and $_.Address -match [regex]::Escape($SearchString)} | %{ | |
$LinksUpdated++ | |
$_.Address = $_.Address.Replace($SearchString,$ReplaceString) | |
} | |
} | |
if ($CopyToNew -and $LinksUpdated) | |
{ | |
$Workbook.SaveAs($_.FullName + " - Copy.xlsx") | |
} | |
if ($LinksUpdated) { | |
$Workbook.Save() | |
$Workbook.Close() | |
} | |
else | |
{ | |
$Workbook.Close($false) | |
} | |
"'{0}': Updated $LinksUpdated links" -f $_.Name | Out-File $LogResultsLocation\Log.log -Append | |
} | |
$Excel.Quit() | |
$Excel = $null | |
[gc]::collect() | |
[gc]::WaitForPendingFinalizers() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment