I am writing a (PnP) Powershell script to update hyperlinks on any word document in a SharePoint online subsite. I have used the following link for guidance.

My script isn't as complex as the link provided as it doesn't need to account for any published/unpublished or previous version scenarios. It simply looks for all hyperlinks within the "current" document in a document library and anything pointing towards a specific address is replaced with a link to a new address.

My script is as follows (after I've loaded PnP / authorised):

add-type -AssemblyName “Microsoft.Office.Interop.Word”
$wdunits = “Microsoft.Office.Interop.Word.wdunits” -as [type]
$donotsave = “Microsoft.Office.Interop.Word.wdDoNotSaveChanges” -as [type]
$save = “Microsoft.Office.Interop.Word.wdSaveChanges” -as [type]
$application = New-Object -ComObject word.application
$application.Visible = $false
$OldName = "https://OLDSITE/dep"
$NewName = "https://tenant.sharepoint.com/teams/dep"

##Get libraries
$libs = Get-PnPList | Where{$_.BaseTemplate -eq 101}

foreach($lib in $libs)
    $libitems = Get-PnPListItem -List $lib -Fields "FileLeafRef"

    foreach($libitem in $libitems)
        write-host "File Name: "$libitem["FileLeafRef"]

        if({$_.Name -match ".doc*"}) 

            $DocumentLocation = $tenancy+$libitem["FileRef"]

            $document = $application.Documents.Open($DocumentLocation)

            $DocURLs = $Document.Hyperlinks

            $URLsToChange = $False

            foreach ($URL in $DocURLs | where {$_.Address -match $OldName})
                write-host "Found an old URL... "$URL.Address
                $NewURLString = $URL.Address 
                $NewURLString = $NewURLString -replace $OldName, $NewName
                $URL.Address = $NewURLString
                write-host "URL is now ... " $URL.Address


            write-host "File Updated"



Upon running the script, the document containing the links I wish to replace is opened with the Save As dialog box, but when I click Save nothing happens - I am however able to save the document under a different filename. This isn't what I want to happen; I want the script to iterate through multiple files, update the links in each and then save the document under its original name without any user intervention.

The account that runs the script is a site collection admin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.