Find and Replace URL Links from Hyperlink Columns in SharePoint
Requirement:
We had a SharePoint portal site called “Crescent Portal” with URL: https://portal.crescent.com. After migrating from SharePoint 2010 to SharePoint 2013, we decided to replace both site name and URL as “Crescent Intranet” with URL “https://intranet.crescent.com”.
We understand there are plenty of lists and libraries hard-coded with the old site URL in its Hyperlink columns. We have to find and replace those old links from all SharePoint lists and libraries.
PowerShell script to find and replace links in Hyperlink columns of SharePoint:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Function Replace-LinkFields($WebURL, $OldLinkURL, $OldLinkTitle, $NewLinkURL, $NewLinkTitle)
{
#Get the Web
$Web = Get-SPWeb $WebURL
#Get all lists - Exclude System lists
$ListCollection = $web.lists | Where-Object { ($_.hidden -eq $false) -and ($_.IsSiteAssetsLibrary -eq $false) -and ($_.Author.LoginName -ne "SHAREPOINT\system") }
#Iterate through each list
foreach ($List in $ListCollection)
{
#find all HyperLink fields in list
$HyperlinkFields = @()
foreach ($field in $list.Fields)
{
if ($field.TypeAsString -eq "URL")
{
$HyperlinkFields = $HyperlinkFields + $field.Title
}
}
write-host "Processing list at: $($web.url)/$($list.RootFolder.Url)"
#Process all hyperlink fields found
#Proceed with next list if Hyperlink field is not found in the list
if($HyperlinkFields.Count -eq 0) { continue }
foreach ($Item in $List.Items)
{
#Iterate through HyperLink fields
foreach ($field in $HyperlinkFields)
{
#Get field value
$FieldValue = $item[$field]
#Skip nulls
if($FieldValue -ne $null)
{
# Check for OldLinkURL or OldLinkTitle
if( ($FieldValue.contains($OldLinkURL)) -or ($FieldValue.contains($OldLinkTitle)) )
{
#Replace the OLD URL with New URL
$Item[$field] = ($item[$field] -Replace $OldLinkURL,$NewLinkURL)
#Replace OLD link title with new link title
$Item[$field] = ($item[$field] -Replace $OldLinkTitle,$NewLinkTitle)
$Item.update()
Write-host "Found and replaced a old link item at: $($web.Url)/$($list.RootFolder.Url) - Item id: $($item.id)"
}
}
}
}
}
}
#Call the function to Replace Links in lists
Replace-LinkFields "https://Intranet.crescent.com/" "https://portal.crescent.com" "Crescent Portal" "https://intranet.crescent.com" "Crescent Intranet"
This script scans all lists and libraries of the given site and replaces old links. You can change the logic to process all sites in the web application to replace the old links across your web application.