We are doing a shared network drive reorganization. This will break links in hundreds of gigs of Excel files that the business uses. In order to soften the blow, I've created a Powershell script that automatically relinks these files. However, it runs super slow at only about 1 MB a minute. It would take several months to relink all Excel files. For now, I am asking the business to restrict the amount of data they are requesting for relinking, however, the faster I can get my script to run, the happier the business will be. It's currently perfectly functional, just slow. Does anyone have any advice for how I can speed up this Powershell script? Any feedback would be appreciated.
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, 'Select the folder where your Excel files are located', 0)
$oldname = "oldname"
$newname = "newname"
if (!$folder -or !$oldname -or !$newname) {exit}
$excel = New-Object -comObject Excel.Application
$excel.Visible = $false
$excel.DisplayAlerts = $false
foreach ($file in Get-ChildItem -literalPath $folder.self.Path*.xls?) {
$workbook = $excel.Workbooks.Open($file.fullname)
foreach ($link in $workbook.LinkSources(1))
{
write-host Old link: $link
$newlink = $link -ireplace [regex]::Escape($oldname), $newname
if (Test-Path $newlink) {
write-host New link: $newlink
$workbook.ChangeLink($link,$newlink,1)
}
else {
write-host New link does not exist: $newlink
}
}
$workbook.Save()
$workbook.Close()
}
$excel.quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()